feat: implementing server framework

This commit is contained in:
Daniel Ledda
2022-06-29 08:24:00 +02:00
parent c628f6b46e
commit bd177c7f09
17 changed files with 210 additions and 55 deletions

View File

@@ -0,0 +1,35 @@
import {StoccaTreDbConn, WithoutId} from "../../database.ts";
import {IngredientModel} from "./IngredientModel.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> {
const result = await this.dbConnection.query<any>(
`INSERT INTO ingredients (id, name, displayName, displayNameDE) VALUES (NULL, '${ingredient.name}', '${ingredient.displayName}', '${ingredient.displayNameDE}');`
);
return result;
}
async getAllIngredients(): Promise<Maybe<IterableIterator<IngredientModel>>> {
if (!this.allGotten) {
const result = await this.dbConnection.query<IngredientModel[]>("SELECT * FROM ingredients");
if (result.just) {
result.just.forEach((ingredient) => this.mapById.set(ingredient.id, ingredient));
} else {
return result;
}
this.allGotten = true;
}
return {
just: this.mapById.values(),
error: null,
};
}
}

View File

@@ -0,0 +1,6 @@
export type IngredientModel = {
id: number,
name: string,
displayName: string,
displayNameDE: string,
};

View File

@@ -0,0 +1,30 @@
import {StoccaTreDbConn} from "/database.ts";
import IngredientCollection from "IngredientCollection.ts";
import StoccaTreRequest from "/StoccaTreRequest.ts";
export default class IngredientResource {
private dbConnection: StoccaTreDbConn;
private collection: IngredientCollection;
constructor(dbConnection: StoccaTreDbConn) {
this.dbConnection = dbConnection;
this.collection = new IngredientCollection(dbConnection);
}
async handleRequest(request: StoccaTreRequest): Promise<Maybe<JSONObject>> {
return await this.allIngredients(request);
}
async allIngredients(request: StoccaTreRequest): Promise<Maybe<JSONObject>> {
const getAllIngredientResult = await this.collection.getAllIngredients();
if (!getAllIngredientResult.error) {
return getAllIngredientResult.just;
}
return {
just: {
ingredients: Array.from(getAllIngredientResult.just),
},
error: "",
};
}
}

View File

@@ -0,0 +1,3 @@
export { type IngredientModel } from "./IngredientModel.ts";
export { default as IngredientCollection } from "./IngredientCollection.ts";
export { default as IngredientResource } from "./IngredientResource.ts";