50 lines
1.8 KiB
TypeScript
50 lines
1.8 KiB
TypeScript
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<number, IngredientModel> = new Map<number, IngredientModel>();
|
|
|
|
constructor(database: StoccaTreDbConn) {
|
|
this.db = database;
|
|
}
|
|
|
|
async addIngredient(ingredient: WithoutId<IngredientModel>): Promise<Result<IngredientModel>> {
|
|
const [error, result] = <Q<IngredientModel>> 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<Result<IngredientModel>> {
|
|
const found = this.mapById.get(id);
|
|
if (found) {
|
|
return [, found];
|
|
}
|
|
const [error, result] = <Q<IngredientModel>> 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<Result<IterableIterator<IngredientModel>>> {
|
|
const [error, result] = <Q<IngredientModel>> 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()];
|
|
}
|
|
}
|