46 lines
1.6 KiB
TypeScript
46 lines
1.6 KiB
TypeScript
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<number, IngredientModel> = new Map<number, IngredientModel>();
|
|
|
|
constructor(database: StoccaTreDbConn) {
|
|
this.db = database;
|
|
}
|
|
|
|
async addIngredient(ingredient: WithoutId<IngredientModel>): Promise<Maybe<IngredientModel[]>> {
|
|
return await this.db.query(sql =>
|
|
sql<IngredientModel[]>`INSERT INTO ingredients ${ sql(ingredient) }`
|
|
);
|
|
}
|
|
|
|
async getById(id: number): Promise<Maybe<IngredientModel>> {
|
|
const found = this.mapById.get(id);
|
|
if (found) {
|
|
return { just: found };
|
|
}
|
|
const result = await this.db.query(sql => sql<IngredientModel[]>`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<Maybe<IterableIterator<IngredientModel>>> {
|
|
const result: Maybe<IngredientModel[]> = await this.db.query(sql =>
|
|
sql<IngredientModel[]>`SELECT * FROM ingredients`
|
|
);
|
|
if (!result.error) {
|
|
result.just.forEach(ingredient => this.mapById.set(ingredient.id, ingredient));
|
|
} else {
|
|
return result;
|
|
}
|
|
return {
|
|
just: this.mapById.values(),
|
|
};
|
|
}
|
|
}
|