import { StoccaTreDbConn, WithoutId } from "../../database.ts"; import { IngredientModel } from "./IngredientModel.ts"; import { Maybe } from "../../Maybe.ts"; export default class IngredientCollection { private db: StoccaTreDbConn; private mapById: Map = new Map(); constructor(database: StoccaTreDbConn) { this.db = database; } async addIngredient(ingredient: WithoutId): Promise> { return await this.db.query(sql => sql`INSERT INTO ingredients ${ sql(ingredient) }` ); } async getById(id: number): Promise> { const found = this.mapById.get(id); if (found) { return { just: found }; } const result = await this.db.query(sql => sql`SELECT * FROM ingredients WHERE id is ${ id }`); if (result.error) { return result; } const ingredient = result.just[0]; this.mapById.set(ingredient.id, ingredient); return { just: ingredient }; } async getAllIngredients(): Promise>> { const result: Maybe = await this.db.query(sql => sql`SELECT * FROM ingredients` ); if (!result.error) { result.just.forEach(ingredient => this.mapById.set(ingredient.id, ingredient)); } else { return result; } return { just: this.mapById.values(), }; } }