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 = new Map(); constructor(database: StoccaTreDbConn) { this.db = database; } async addUser(user: WithoutId): Promise> { 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] = > 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> { const [error, users] = > 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())]; } }