feat: new user resource integrating postgresql

This commit is contained in:
Daniel Ledda
2022-07-08 09:31:34 +02:00
parent 3e5c53f9f5
commit ba68f953f0
18 changed files with 281 additions and 121 deletions

View File

@@ -1,45 +1,48 @@
import {StoccaTreDbConn} from "../../database.ts";
import IngredientCollection from "./IngredientCollection.ts";
import StoccaTreRequest from "../../StoccaTreRequest.ts";
import StoccaTreRequest, {RouteDefinition} from "../../StoccaTreRequest.ts";
import {Maybe} from "../../Maybe.ts";
import {JSONObject} from "../../JSON.ts";
import {IngredientModel} from "./IngredientModel.ts";
import {IngredientSchemaWithoutId} from "./IngredientModel.ts";
export default class IngredientResource {
private dbConnection: StoccaTreDbConn;
private collection: IngredientCollection;
private routes: Readonly<Record<string, RouteDefinition>> = {
Add: {
pattern: /\/add/,
method: "POST"
},
GetAll: {
pattern: /\/all/,
method: "GET"
},
} as const;
constructor(dbConnection: StoccaTreDbConn) {
this.dbConnection = dbConnection;
this.collection = new IngredientCollection(dbConnection);
}
static isIngredient(json: JSONObject): json is IngredientModel {
if (json) {
return true;
}
return false;
}
async handleRequest(request: StoccaTreRequest): Promise<Maybe<JSONObject>> {
switch (request.route) {
case "/add":
if (request.method === "POST") {
const ingredient = JSON.parse(request.body ?? "");
return await this.collection.addIngredient(JSON.parse(request.body));
}
break;
case "/all":
return await this.allIngredients(request);
default:
break;
if (request.match(this.routes.Add)) {
return await this.addIngredient(request);
}
return { error: {message: "Invalid route" }};
if (request.match(this.routes.GetAll)) {
return await this.allIngredients(request);
}
return { error: { message: "Invalid route" }};
}
async allIngredients(request: StoccaTreRequest): Promise<Maybe<JSONObject>> {
private async addIngredient(request: StoccaTreRequest): Promise<Maybe<{ insertedId: number }>> {
const ingredient = IngredientSchemaWithoutId.safeParse(JSON.parse(request.body ?? "{}"));
if (!ingredient.success) {
return { error: new Error("Ingredient was malformed.") };
}
return await this.collection.addIngredient(ingredient.data);
}
private async allIngredients(request: StoccaTreRequest): Promise<Maybe<JSONObject>> {
const getAllIngredientResult = await this.collection.getAllIngredients();
if (getAllIngredientResult.error) {
return getAllIngredientResult;