61 lines
1.7 KiB
TypeScript
61 lines
1.7 KiB
TypeScript
import {
|
|
ConflictException,
|
|
Injectable,
|
|
NotFoundException,
|
|
} from '@nestjs/common';
|
|
import { InjectRepository } from '@nestjs/typeorm';
|
|
import { Repository } from 'typeorm';
|
|
import { CreateUserDto } from './dto/create-user.dto';
|
|
import { UpdateUserDto } from './dto/update-user.dto';
|
|
import { User } from './entities/user.entity';
|
|
|
|
@Injectable()
|
|
export class UsersService {
|
|
constructor(
|
|
@InjectRepository(User)
|
|
private readonly usersRepository: Repository<User>,
|
|
) {}
|
|
|
|
async create(createUserDto: CreateUserDto): Promise<User> {
|
|
await this.ensureMobileIsUnique(createUserDto.mobile);
|
|
const user = this.usersRepository.create(createUserDto);
|
|
return this.usersRepository.save(user);
|
|
}
|
|
|
|
findAll(): Promise<User[]> {
|
|
return this.usersRepository.find();
|
|
}
|
|
|
|
async findOne(id: string): Promise<User> {
|
|
const user = await this.usersRepository.findOneBy({ id });
|
|
if (!user) {
|
|
throw new NotFoundException(`User #${id} not found`);
|
|
}
|
|
return user;
|
|
}
|
|
|
|
async update(id: string, updateUserDto: UpdateUserDto): Promise<User> {
|
|
const user = await this.findOne(id);
|
|
if (updateUserDto.mobile) {
|
|
await this.ensureMobileIsUnique(updateUserDto.mobile, id);
|
|
}
|
|
Object.assign(user, updateUserDto);
|
|
return this.usersRepository.save(user);
|
|
}
|
|
|
|
async remove(id: string): Promise<void> {
|
|
const user = await this.findOne(id);
|
|
await this.usersRepository.remove(user);
|
|
}
|
|
|
|
private async ensureMobileIsUnique(
|
|
mobile: string,
|
|
excludeUserId?: string,
|
|
): Promise<void> {
|
|
const existing = await this.usersRepository.findOneBy({ mobile });
|
|
if (existing && existing.id !== excludeUserId) {
|
|
throw new ConflictException('Mobile number already exists');
|
|
}
|
|
}
|
|
}
|