feat: things are happening...
This commit is contained in:
@@ -1,7 +1,9 @@
|
||||
import * as bcrypt from "bcrypt";
|
||||
import { StoccaTreDbConn, WithoutId } from "../../database.ts";
|
||||
import {Q, StoccaTreDbConn, WithoutId} from "../../database.ts";
|
||||
import { UserModel } from "./UserModel.ts";
|
||||
import { Maybe } from "../../Maybe.ts";
|
||||
import {Result, StoccaTreError} from "../../Result.ts";
|
||||
|
||||
const TABLE_NAME = "main.users";
|
||||
|
||||
export default class UserCollection {
|
||||
private db: StoccaTreDbConn;
|
||||
@@ -11,40 +13,34 @@ export default class UserCollection {
|
||||
this.db = database;
|
||||
}
|
||||
|
||||
async addUser(user: WithoutId<UserModel>): Promise<Maybe<{ insertedId: number }>> {
|
||||
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 { error: { message: error.message }};
|
||||
return [new StoccaTreError(error.message)];
|
||||
}
|
||||
return { error: new Error("Failed to create user") };
|
||||
return [new StoccaTreError("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;
|
||||
const [error, users] = <Q<UserModel>> await this.db.query(`INSERT INTO ${TABLE_NAME} ($displayName, $password) RETURNING *`, user);
|
||||
if (error) {
|
||||
return [error];
|
||||
}
|
||||
return {
|
||||
just: { insertedId: result.just[0]?.id ?? NaN }
|
||||
if (users.length === 0) {
|
||||
return [new StoccaTreError("Failed to insert user.")];
|
||||
}
|
||||
|
||||
return [, users[0]];
|
||||
}
|
||||
|
||||
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;
|
||||
async getAllUsers(): Promise<Result<UserModel[]>> {
|
||||
const [error, users] = <Q<UserModel>> await this.db.query(`SELECT * FROM ${TABLE_NAME}`);
|
||||
if (error) {
|
||||
return [error];
|
||||
}
|
||||
return {
|
||||
just: Array.from(this.mapById.values()),
|
||||
};
|
||||
users.forEach((user) => this.mapById.set(user.id, user));
|
||||
return [, Array.from(this.mapById.values())];
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user