53 lines
1.8 KiB
TypeScript
53 lines
1.8 KiB
TypeScript
import { StoccaTreDbConn } from "../../database.ts";
|
|
import StoccaTreRequest, { RouteDefinition } from "../../StoccaTreRequest.ts";
|
|
import {Result, StoccaTreError} from "../../Result.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<Result<JSONObject> | null> {
|
|
if (request.match(this.routes.Add)) {
|
|
return await this.addUser(request);
|
|
}
|
|
if (request.match(this.routes.GetAll)) {
|
|
return await this.allUsers(request);
|
|
}
|
|
return null;
|
|
}
|
|
|
|
private async addUser(request: StoccaTreRequest): Promise<Result<{ id: number }>> {
|
|
const user = UserSchemaWithoutId.safeParse(request.body);
|
|
if (!user.success) {
|
|
return [new StoccaTreError("User definition was malformed.", 400)];
|
|
}
|
|
return await this.collection.addUser(user.data);
|
|
}
|
|
|
|
private async allUsers(request: StoccaTreRequest): Promise<Result<JSONObject>> {
|
|
const [error, result] = await this.collection.getAllUsers();
|
|
if (error) {
|
|
return [error];
|
|
}
|
|
return [, { users: result }];
|
|
}
|
|
}
|