import { StoccaTreDbConn } from "../../database.ts"; import IngredientCollection from "./IngredientCollection.ts"; import StoccaTreRequest, { RouteDefinition } from "../../StoccaTreRequest.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> = { 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 | null> { let result; if (request.match(this.routes.Add)) { result = await this.addIngredient(request); } if (request.match(this.routes.GetAll)) { result = await this.allIngredients(request); } 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> { 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> { const [error, ingredients] = await this.collection.getAllIngredients(); if (error) { return [error]; } return [, { ingredients: Array.from(ingredients), }]; } }