Files
negareh-api/src/modules/user/providers/user.service.ts
T
2026-01-25 09:35:01 +03:30

73 lines
2.0 KiB
TypeScript

import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { RequiredEntityData } from '@mikro-orm/core';
import { User } from '../entities/user.entity';
import { EntityManager } from '@mikro-orm/postgresql';
import { CreateUserDto } from '../dto/create-user.dto';
import { FindUsersDto } from '../dto/find-user.dto';
import { PaginatedResult } from 'src/common/interfaces/pagination.interface';
import { UserRepository } from '../repositories/user.repository';
import { normalizePhone } from '../../util/phone.util';
import { UpdateUserDto } from '../dto/update-user.dto';
@Injectable()
export class UserService {
constructor(
private readonly userRepository: UserRepository,
private readonly em: EntityManager,
) { }
async getOrCreate(dto: CreateUserDto): Promise<User> {
const normalizedPhone = normalizePhone(dto.phone)
const currentUser = await this.userRepository.findOne({ phone: normalizedPhone });
if (currentUser) {
return currentUser
}
const createData: RequiredEntityData<User> = {
phone: normalizedPhone,
firstName: dto.firstName,
lastName: dto.lastName,
gender: dto.gender,
maxCredit: dto.maxCredit
};
const user = this.userRepository.create(createData);
await this.em.persistAndFlush([user]);
return user;
}
async findByPhone(phone: string): Promise<User | null> {
const normalizedPhone = normalizePhone(phone);
return this.userRepository.findOne({ phone: normalizedPhone });
}
async findById(id: string): Promise<User | null> {
return this.userRepository.findOne({ id });
}
async updateUser(userId: string, dto: UpdateUserDto): Promise<User> {
const user = await this.userRepository.findOne({ id: userId });
if (!user) {
throw new NotFoundException(`User with ID ${userId} not found.`);
}
this.em.assign(user, dto);
await this.em.flush();
return user;
}
async findAll(dto: FindUsersDto): Promise<PaginatedResult<User>> {
return this.userRepository.findAllPaginated(dto)
}
}