refactor: some stuff

This commit is contained in:
Daniel Ledda
2022-07-18 08:28:19 +02:00
parent c9f2d2720c
commit 3390a17ad9
8 changed files with 56 additions and 64 deletions

View File

@@ -1,10 +1,21 @@
import { Q, StoccaTreDbConn, WithoutId } from "../../database.ts";
import { IngredientModel } from "./IngredientModel.ts";
import { z } from "zod";
import { JSONObject } from "../../JSON.ts";
import { Q, StoccaTreDbConn } from "../../database.ts";
import { Result, StoccaTreError } from "../../Result.ts";
const TABLE_NAME = "main.ingredients";
export const IngredientSchema = z.object({
id: z.number(),
name: z.string().nonempty(),
displayName: z.string().nonempty(),
displayNameDE: z.string().nonempty(),
});
export const IngredientSchemaWithoutId = IngredientSchema.omit({ id: true });
export type IngredientModel = z.infer<typeof IngredientSchema>;
export default class IngredientCollection {
static readonly TABLE_NAME = "main.ingredients";
private db: StoccaTreDbConn;
private mapById: Map<number, IngredientModel> = new Map<number, IngredientModel>();
@@ -12,8 +23,15 @@ export default class IngredientCollection {
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);
async addIngredient(ingredient: JSONObject): Promise<Result<IngredientModel>> {
const parsed = IngredientSchemaWithoutId.safeParse(ingredient);
if (!ingredient.success) {
return [new StoccaTreError("Ingredient definition was malformed.", 400)];
}
const [error, result] = <Q<IngredientModel>> await this.db.query(
`INSERT INTO ${ IngredientCollection.TABLE_NAME } VALUES (DEFAULT, $name, $displayName, $displayNameDE) RETURNING *;`,
parsed
);
if (error) {
return [error];
}
@@ -28,7 +46,7 @@ export default class IngredientCollection {
if (found) {
return [, found];
}
const [error, result] = <Q<IngredientModel>> await this.db.query(`SELECT * FROM ${ TABLE_NAME } WHERE id is $id`, { id });
const [error, result] = <Q<IngredientModel>> await this.db.query(`SELECT * FROM ${ IngredientCollection.TABLE_NAME } WHERE id is $id`, { id });
if (error) {
return [error];
}
@@ -37,13 +55,13 @@ export default class IngredientCollection {
return [, ingredient];
}
async getAllIngredients(): Promise<Result<IterableIterator<IngredientModel>>> {
const [error, result] = <Q<IngredientModel>> await this.db.query(`SELECT * FROM ${ TABLE_NAME }`);
async getAllIngredients(): Promise<Result<IngredientModel[]>> {
const [error, result] = <Q<IngredientModel>> await this.db.query(`SELECT * FROM ${ IngredientCollection.TABLE_NAME }`);
if (!error) {
result.forEach((ingredient: IngredientModel) => this.mapById.set(ingredient.id, ingredient));
} else {
return [error];
}
return [, this.mapById.values()];
return [, Array.from(this.mapById.values())];
}
}