39 lines
1.1 KiB
TypeScript
39 lines
1.1 KiB
TypeScript
import { Injectable, ConflictException } from '@nestjs/common';
|
|
import { InjectRepository } from '@nestjs/typeorm';
|
|
import { Repository } from 'typeorm';
|
|
import { User } from './user.entity';
|
|
import * as bcrypt from 'bcrypt';
|
|
|
|
@Injectable()
|
|
export class UsersService {
|
|
constructor(
|
|
@InjectRepository(User)
|
|
private usersRepository: Repository<User>
|
|
) {}
|
|
|
|
async create(userData: Partial<User>): Promise<User> {
|
|
if (!userData.password) {
|
|
throw new ConflictException('Password is required');
|
|
}
|
|
|
|
const hashedPassword = await bcrypt.hash(userData.password, 10);
|
|
|
|
const user = this.usersRepository.create({
|
|
username: userData.username as string,
|
|
email: userData.email as string,
|
|
password: hashedPassword,
|
|
});
|
|
|
|
return await this.usersRepository.save(user);
|
|
}
|
|
|
|
async findOneByUsername(username: string): Promise<User | null> {
|
|
return await this.usersRepository.findOne({ where: { username } });
|
|
}
|
|
|
|
async findOneById(id: number): Promise<User | null> {
|
|
return await this.usersRepository.findOne({ where: { id } });
|
|
}
|
|
|
|
}
|