Files
stocca-tre/server/resources/user/UserCollection.ts
2022-07-10 23:07:51 +02:00

47 lines
1.6 KiB
TypeScript

import * as bcrypt from "bcrypt";
import {Q, StoccaTreDbConn, WithoutId} from "../../database.ts";
import { UserModel } from "./UserModel.ts";
import {Result, StoccaTreError} from "../../Result.ts";
const TABLE_NAME = "main.users";
export default class UserCollection {
private db: StoccaTreDbConn;
private mapById: Map<number, UserModel> = new Map<number, UserModel>();
constructor(database: StoccaTreDbConn) {
this.db = database;
}
async addUser(user: WithoutId<UserModel>): Promise<Result<{ id: number }>> {
let hash: string;
try {
hash = await bcrypt.hash(user.password);
} catch (e: unknown) {
const error = e as { message?: string };
if (typeof error.message === "string") {
return [new StoccaTreError(error.message)];
}
return [new StoccaTreError("Failed to create user")];
}
user.password = hash;
const [error, users] = <Q<UserModel>> await this.db.query(`INSERT INTO ${TABLE_NAME} ($displayName, $password) RETURNING *`, user);
if (error) {
return [error];
}
if (users.length === 0) {
return [new StoccaTreError("Failed to insert user.")];
}
return [, users[0]];
}
async getAllUsers(): Promise<Result<UserModel[]>> {
const [error, users] = <Q<UserModel>> await this.db.query(`SELECT * FROM ${TABLE_NAME}`);
if (error) {
return [error];
}
users.forEach((user) => this.mapById.set(user.id, user));
return [, Array.from(this.mapById.values())];
}
}