Mobile number already exists
This commit is contained in:
@@ -1,4 +1,8 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import {
|
||||
ConflictException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { CreateUserDto } from './dto/create-user.dto';
|
||||
@@ -12,7 +16,8 @@ export class UsersService {
|
||||
private readonly usersRepository: Repository<User>,
|
||||
) {}
|
||||
|
||||
create(createUserDto: CreateUserDto): Promise<User> {
|
||||
async create(createUserDto: CreateUserDto): Promise<User> {
|
||||
await this.ensureMobileIsUnique(createUserDto.mobile);
|
||||
const user = this.usersRepository.create(createUserDto);
|
||||
return this.usersRepository.save(user);
|
||||
}
|
||||
@@ -31,6 +36,9 @@ export class UsersService {
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -39,4 +47,14 @@ export class UsersService {
|
||||
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');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user