refactor: some stuff
This commit is contained in:
@@ -1,12 +1,10 @@
|
||||
import { StoccaTreDbConn } from "../../database.ts";
|
||||
import IngredientCollection from "./IngredientCollection.ts";
|
||||
import StoccaTreRequest, { RouteDefinition } from "../../StoccaTreRequest.ts";
|
||||
import {Result, StoccaTreError} from "../../Result.ts";
|
||||
import { Result, StoccaTreError } from "../../Result.ts";
|
||||
import { JSONObject } from "../../JSON.ts";
|
||||
import { IngredientModel, IngredientSchemaWithoutId } from "./IngredientModel.ts";
|
||||
|
||||
export default class IngredientResource {
|
||||
private dbConnection: StoccaTreDbConn;
|
||||
private collection: IngredientCollection;
|
||||
private routes: Readonly<Record<string, RouteDefinition>> = {
|
||||
Add: {
|
||||
@@ -20,44 +18,17 @@ export default class IngredientResource {
|
||||
} as const;
|
||||
|
||||
constructor(dbConnection: StoccaTreDbConn) {
|
||||
this.dbConnection = dbConnection;
|
||||
this.collection = new IngredientCollection(dbConnection);
|
||||
}
|
||||
|
||||
async handleRequest(request: StoccaTreRequest): Promise<Result<JSONObject> | null> {
|
||||
let result;
|
||||
if (request.match(this.routes.Add)) {
|
||||
result = await this.addIngredient(request);
|
||||
let result = null;
|
||||
if (request.match(this.routes.Add) && request.body) {
|
||||
result = await this.collection.addIngredient(request.body);
|
||||
}
|
||||
if (request.match(this.routes.GetAll)) {
|
||||
result = await this.allIngredients(request);
|
||||
result = await this.collection.getAllIngredients();
|
||||
}
|
||||
if (result) {
|
||||
const [error] = result;
|
||||
if (error) {
|
||||
return [error.qualified("Could not fulfill ingredient request: ")];
|
||||
} else {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private async addIngredient(request: StoccaTreRequest): Promise<Result<{ id: number }>> {
|
||||
const ingredient = IngredientSchemaWithoutId.safeParse(request.body);
|
||||
if (!ingredient.success) {
|
||||
return [new StoccaTreError("Ingredient definition was malformed.", 400)];
|
||||
}
|
||||
return await this.collection.addIngredient(ingredient.data);
|
||||
}
|
||||
|
||||
private async allIngredients(request: StoccaTreRequest): Promise<Result<JSONObject>> {
|
||||
const [error, ingredients] = await this.collection.getAllIngredients();
|
||||
if (error) {
|
||||
return [error];
|
||||
}
|
||||
return [, {
|
||||
ingredients: Array.from(ingredients),
|
||||
}];
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user