57 lines
1.8 KiB
TypeScript
57 lines
1.8 KiB
TypeScript
import {StoccaTreDbConn} from "../../database.ts";
|
|
import StoccaTreRequest, {RouteDefinition} from "../../StoccaTreRequest.ts";
|
|
import {Maybe} from "../../Maybe.ts";
|
|
import {JSONObject} from "../../JSON.ts";
|
|
import UserCollection from "./UserCollection.ts";
|
|
import {UserSchemaWithoutId} from "./UserModel.ts";
|
|
|
|
export default class UserResource {
|
|
private dbConnection: StoccaTreDbConn;
|
|
private collection: UserCollection;
|
|
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 UserCollection(dbConnection);
|
|
}
|
|
|
|
async handleRequest(request: StoccaTreRequest): Promise<Maybe<JSONObject>> {
|
|
if (request.match(this.routes.Add)) {
|
|
return await this.addUser(request);
|
|
}
|
|
if (request.match(this.routes.GetAll)) {
|
|
return await this.allUsers(request);
|
|
}
|
|
return { error: { message: "Invalid route" }};
|
|
}
|
|
|
|
private async addUser(request: StoccaTreRequest): Promise<Maybe<{ insertedId: number }>> {
|
|
const user = UserSchemaWithoutId.safeParse(JSON.parse(request.body ?? "{}"));
|
|
if (!user.success) {
|
|
return { error: new Error("Ingredient was malformed.") };
|
|
}
|
|
return await this.collection.addUser(user.data);
|
|
}
|
|
|
|
private async allUsers(request: StoccaTreRequest): Promise<Maybe<JSONObject>> {
|
|
const allUsers = await this.collection.getAllUsers();
|
|
if (allUsers.error) {
|
|
return allUsers;
|
|
}
|
|
return {
|
|
just: {
|
|
ingredients: Array.from(allUsers.just),
|
|
},
|
|
};
|
|
}
|
|
}
|