51 lines
1.6 KiB
TypeScript
51 lines
1.6 KiB
TypeScript
import * as bcrypt from "bcrypt";
|
|
import { StoccaTreDbConn, WithoutId } from "../../database.ts";
|
|
import { UserModel } from "./UserModel.ts";
|
|
import { Maybe } from "../../Maybe.ts";
|
|
|
|
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<Maybe<{ insertedId: 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 { error: { message: error.message }};
|
|
}
|
|
return { error: new Error("Failed to create user") };
|
|
}
|
|
user.password = hash;
|
|
const result: Maybe<UserModel[]> = await this.db.query(sql => sql`
|
|
INSERT INTO users ${ sql(user, "displayName") }
|
|
RETURNING *
|
|
`);
|
|
if (result.error) {
|
|
return result;
|
|
}
|
|
return {
|
|
just: { insertedId: result.just[0]?.id ?? NaN }
|
|
}
|
|
|
|
}
|
|
|
|
async getAllUsers(): Promise<Maybe<UserModel[]>> {
|
|
const result = await this.db.query((sql) => sql<UserModel[]>`SELECT * FROM users`);
|
|
if (!result.error) {
|
|
result.just.forEach(user => this.mapById.set(user.id, user));
|
|
} else {
|
|
return result;
|
|
}
|
|
return {
|
|
just: Array.from(this.mapById.values()),
|
|
};
|
|
}
|
|
}
|