import { ConflictException, Injectable } from '@nestjs/common'; import { DatabaseClient } from '../database/database.client.js'; import type { User } from './user.js'; type UserRow = { id: string; username: string; display_name: string; password_hash: string; created_at: Date | string; }; function toUser(row: UserRow): User { return { id: row.id, username: row.username, display_name: row.display_name, created_at: new Date(row.created_at).toISOString(), }; } @Injectable() export class UsersRepository { constructor(private readonly database: DatabaseClient) {} async findById(id: string): Promise { const result = await this.database.query( 'users.findById', 'SELECT id, username, display_name, password_hash, created_at FROM users WHERE id = $1', [id], ); const row = result.rows[0]; return row ? toUser(row) : undefined; } async findByUsername( username: string, ): Promise<(User & { password_hash: string }) | undefined> { const result = await this.database.query( 'users.findByUsername', 'SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = $1', [username], ); const row = result.rows[0]; return row ? { ...toUser(row), password_hash: row.password_hash } : undefined; } async create(user: { id: string; username: string; display_name: string; password_hash: string; }): Promise { try { const result = await this.database.query( 'users.insert', `INSERT INTO users (id, username, display_name, password_hash) VALUES ($1, $2, $3, $4) RETURNING id, username, display_name, password_hash, created_at`, [user.id, user.username, user.display_name, user.password_hash], ); return toUser(result.rows[0]); } catch (error) { if ((error as { code?: string }).code === '23505') throw new ConflictException('Username already exists'); throw error; } } }