File: /var/www/api-parametros/src/app/proyectos/services/proyecto.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Proyecto } from '../../proyectos/schemas/proyecto.schema';
import { CreateProyectoDto } from '../dto/create-proyecto.dto';
import { UpdateProyectoDto } from '../dto/update-proyecto.dto';
import { handleValidationError } from '../../../shared/utils/error-handler';
import {
handleMessageError,
handleMessageSucces,
} from '../../../shared/utils/message-handler';
import { ResApiInterface } from '../../../shared/interfaces/res-api.interface';
@Injectable()
export class ProyectoService {
constructor(
@InjectModel(Proyecto.name) private proyectoModel: Model<Proyecto>,
) {}
async create(
createProyectoDto: CreateProyectoDto,
): Promise<ResApiInterface<CreateProyectoDto>> {
try {
const createdProyecto = new this.proyectoModel(createProyectoDto);
const savedProyecto = await createdProyecto.save();
return handleMessageSucces(savedProyecto, 'create');
} catch (error) {
throw handleValidationError(error);
}
}
async findAll(
page: number,
pageSize: number,
): Promise<ResApiInterface<CreateProyectoDto[]>> {
try {
const skip = (page - 1) * pageSize;
const totalRecordsPromise = await this.proyectoModel.countDocuments({
deletedAt: { $in: null },
});
const proyectosPromise = this.proyectoModel
.find({ deletedAt: { $in: null } }, '_id nombre descripcion createdAt')
.skip(skip)
.limit(pageSize)
.exec();
const [proyectos, totalRecords] = await Promise.all([
proyectosPromise,
totalRecordsPromise,
]);
return handleMessageSucces(proyectos, 'findAll', totalRecords);
} catch (error) {
throw handleValidationError(error);
}
}
async findOne(id: string): Promise<ResApiInterface<CreateProyectoDto>> {
try {
const proyecto = await this.proyectoModel
.findById(id, '_id nombre descripcion')
.exec();
if (!proyecto) {
throw new NotFoundException(handleMessageError('notFound'));
}
return handleMessageSucces(proyecto, 'findOne');
} catch (error) {
throw handleValidationError(error);
}
}
async update(
id: string,
updateProyectoDto: UpdateProyectoDto,
): Promise<ResApiInterface<UpdateProyectoDto>> {
try {
const updatedProyecto = await this.proyectoModel.findByIdAndUpdate(
id,
updateProyectoDto,
{ new: true },
);
if (!updatedProyecto) {
throw new NotFoundException(handleMessageError('notFound'));
}
return handleMessageSucces(updatedProyecto, 'update');
} catch (error) {
throw handleValidationError(error);
}
}
async delete(id: string): Promise<ResApiInterface<CreateProyectoDto>> {
try {
const deletedProyecto = await this.proyectoModel.findByIdAndUpdate(id, {
deletedAt: new Date(),
});
if (!deletedProyecto) {
throw new NotFoundException(handleMessageError('notFound'));
}
return handleMessageSucces(deletedProyecto, 'delete');
} catch (error) {
throw handleValidationError(error);
}
}
}