Files
stocca-tre/server/resources/ingredient/IngredientCollection.ts
2022-06-30 08:33:13 +02:00

35 lines
1.3 KiB
TypeScript

import {StoccaTreDbConn, WithoutId} from "../../database.ts";
import {IngredientModel} from "./IngredientModel.ts";
import {Maybe} from "../../Maybe.ts";
export default class IngredientCollection {
private dbConnection: StoccaTreDbConn;
private mapById: Map<number, IngredientModel> = new Map<number, IngredientModel>();
private allGotten = false;
constructor(database: StoccaTreDbConn) {
this.dbConnection = database;
}
async addIngredient(ingredient: WithoutId<IngredientModel>): Promise<any> {
return await this.dbConnection.query<any>(
`INSERT INTO ingredients (id, name, displayName, displayNameDE) VALUES (NULL, '${ingredient.name}', '${ingredient.displayName}', '${ingredient.displayNameDE}');`
);
}
async getAllIngredients(): Promise<Maybe<IterableIterator<IngredientModel>>> {
if (!this.allGotten) {
const result = await this.dbConnection.query<IngredientModel[]>("SELECT * FROM ingredients");
if (!result.error) {
result.just.forEach((ingredient: IngredientModel) => this.mapById.set(ingredient.id, ingredient));
} else {
return result;
}
this.allGotten = true;
}
return {
just: this.mapById.values(),
};
}
}