feat: new user resource integrating postgresql
This commit is contained in:
56
server/resources/user/UserResource.ts
Normal file
56
server/resources/user/UserResource.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
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),
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user