forked from mtusi2026/mtusi2026lab6
49 lines
1.2 KiB
TypeScript
49 lines
1.2 KiB
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import { hashPassword } from '../auth/password';
|
|
import { ApiError } from '../common/filters/api-error';
|
|
import { User } from '../common/domain';
|
|
import { PrismaService, isUniqueViolation } from '../db/prisma.service';
|
|
|
|
@Injectable()
|
|
export class UsersService {
|
|
constructor(private readonly prisma: PrismaService) {}
|
|
|
|
async register(
|
|
username: string,
|
|
displayName: string,
|
|
password: string,
|
|
): Promise<User> {
|
|
const passwordHash = await hashPassword(password);
|
|
try {
|
|
const row = await this.prisma.user.create({
|
|
data: { username, displayName: displayName.trim(), passwordHash },
|
|
});
|
|
return toUser(row);
|
|
} catch (error) {
|
|
if (isUniqueViolation(error)) {
|
|
throw new ApiError('conflict', 'username is already taken');
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async findById(id: string): Promise<User | null> {
|
|
const row = await this.prisma.user.findUnique({ where: { id } });
|
|
return row ? toUser(row) : null;
|
|
}
|
|
}
|
|
|
|
export function toUser(row: {
|
|
id: string;
|
|
username: string;
|
|
displayName: string;
|
|
createdAt: Date;
|
|
}): User {
|
|
return {
|
|
id: row.id,
|
|
username: row.username,
|
|
displayName: row.displayName,
|
|
createdAt: row.createdAt.toISOString(),
|
|
};
|
|
}
|