1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import { BadRequestException, Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Address } from '../../database/schemas/address.schema';
import { User, UserDocument } from '../../database/schemas/user.schema';
import { EncryptorService } from '../../security/encryptor.service';
import { UserCreateDto } from './user.dto';
@Injectable()
export class UserService {
private readonly logger = new Logger(UserService.name);
constructor(
@InjectModel(User.name)
private readonly userModel: Model<UserDocument>,
private readonly encryptor: EncryptorService,
) {}
async create(dto: UserCreateDto): Promise<UserDocument> {
const user = await this.findByEmailOrCpfOrTelefone(
dto.email,
dto.cpf,
dto.telefone,
);
if (!user) {
const model = this.dtoToModel({
...dto,
password: await this.encryptor.encrypt(dto.password),
});
return this.userModel.create(model);
} else {
throw new BadRequestException('Usuário já existe');
}
}
async findById(id: string): Promise<UserDocument> {
try {
const user = await this.userModel.findById(id);
return user;
} catch (error) {
this.logger.error(error);
return null;
}
}
async findByEmailOrCpfOrTelefone(
email?: string,
cpf?: string,
telefone?: string,
): Promise<UserDocument> {
return await this.userModel.findOne({
$or: [{ email: email }, { cpf: cpf }, { telefone: telefone }],
});
}
async findByEmailAndPassword(
email: string,
password: string,
): Promise<UserDocument> {
return this.userModel.findOne({ email, password });
}
async findAll(): Promise<UserDocument[]> {
return this.userModel.find().exec();
}
private dtoToModel(dto: UserCreateDto): User {
return {
administrador: false,
endereco: {
cep: dto.cep,
} as Address, // TODO: buscar endereço pelo CEP e preencher outros dados
contatoEmergencia: dto.contatoEmergencia,
contatosProfissionais: [],
cpf: dto.cpf,
email: dto.email,
nome: dto.nome,
password: dto.password,
telefone: dto.telefone,
numeroINSS: dto.numeroINSS,
};
}
}