Files
stocca-tre/server/resources/ingredient/IngredientResource.ts
2022-07-08 09:31:34 +02:00

56 lines
2.0 KiB
TypeScript

import {StoccaTreDbConn} from "../../database.ts";
import IngredientCollection from "./IngredientCollection.ts";
import StoccaTreRequest, {RouteDefinition} from "../../StoccaTreRequest.ts";
import {Maybe} from "../../Maybe.ts";
import {JSONObject} from "../../JSON.ts";
import {IngredientSchemaWithoutId} from "./IngredientModel.ts";
export default class IngredientResource {
private dbConnection: StoccaTreDbConn;
private collection: IngredientCollection;
private routes: Readonly<Record<string, RouteDefinition>> = {
Add: {
pattern: /\/add/,
method: "POST"
},
GetAll: {
pattern: /\/all/,
method: "GET"
},
} as const;
constructor(dbConnection: StoccaTreDbConn) {
this.dbConnection = dbConnection;
this.collection = new IngredientCollection(dbConnection);
}
async handleRequest(request: StoccaTreRequest): Promise<Maybe<JSONObject>> {
if (request.match(this.routes.Add)) {
return await this.addIngredient(request);
}
if (request.match(this.routes.GetAll)) {
return await this.allIngredients(request);
}
return { error: { message: "Invalid route" }};
}
private async addIngredient(request: StoccaTreRequest): Promise<Maybe<{ insertedId: number }>> {
const ingredient = IngredientSchemaWithoutId.safeParse(JSON.parse(request.body ?? "{}"));
if (!ingredient.success) {
return { error: new Error("Ingredient was malformed.") };
}
return await this.collection.addIngredient(ingredient.data);
}
private async allIngredients(request: StoccaTreRequest): Promise<Maybe<JSONObject>> {
const getAllIngredientResult = await this.collection.getAllIngredients();
if (getAllIngredientResult.error) {
return getAllIngredientResult;
}
return {
just: {
ingredients: Array.from(getAllIngredientResult.just),
},
};
}
}