import { Q, StoccaTreDbConn, WithoutId } from "../../database.ts"; import { IngredientModel } from "./IngredientModel.ts"; import { Result, StoccaTreError } from "../../Result.ts"; const TABLE_NAME = "main.ingredients"; export default class IngredientCollection { private db: StoccaTreDbConn; private mapById: Map = new Map(); constructor(database: StoccaTreDbConn) { this.db = database; } async addIngredient(ingredient: WithoutId): Promise> { const [error, result] = > await this.db.query(`INSERT INTO ${ TABLE_NAME } VALUES (DEFAULT, $name, $displayName, $displayNameDE) RETURNING *;`, ingredient); if (error) { return [error]; } if (result.length > 0) { return [, result[0]]; } return [new StoccaTreError("Ingredient wasn't inserted!")]; } async getById(id: number): Promise> { const found = this.mapById.get(id); if (found) { return [, found]; } const [error, result] = > await this.db.query(`SELECT * FROM ${ TABLE_NAME } WHERE id is $id`, { id }); if (error) { return [error]; } const ingredient = result[0]; this.mapById.set(ingredient.id, ingredient); return [, ingredient]; } async getAllIngredients(): Promise>> { const [error, result] = > await this.db.query(`SELECT * FROM ${ TABLE_NAME }`); if (!error) { result.forEach((ingredient: IngredientModel) => this.mapById.set(ingredient.id, ingredient)); } else { return [error]; } return [, this.mapById.values()]; } }