Files
pcpuma_unam_api/src/modulo/modulo.service.ts
T

80 lines
2.3 KiB
TypeScript
Raw Normal View History

2022-04-16 13:05:27 -05:00
import {
ConflictException,
Injectable,
NotFoundException,
} from '@nestjs/common';
2022-04-04 20:02:54 -05:00
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
2022-05-02 15:50:00 -05:00
import { Institucion } from 'src/institucion/entity/institucion.entity';
2022-04-16 14:37:17 -05:00
import { Modulo } from './entity/modulo.entity';
2022-04-17 21:55:00 -05:00
import { InstitucionService } from '../institucion/institucion.service';
2022-04-04 20:02:54 -05:00
@Injectable()
export class ModuloService {
constructor(
2022-04-18 16:55:19 -05:00
@InjectRepository(Modulo) private repository: Repository<Modulo>,
private institucionService: InstitucionService,
2022-04-04 20:02:54 -05:00
) {}
async create(id_institucion: number, modulo: string) {
const institucion = await this.institucionService.findById(id_institucion);
2022-05-02 15:50:00 -05:00
return this.existeModulo(institucion, modulo)
.then(() =>
this.repository.save(
this.repository.create({
institucion,
modulo,
}),
),
)
.then((_) => ({ message: 'Se creo correctamente el módulo.' }));
}
async existeModulo(id_institucion: number | Institucion, modulo: string) {
const institucion =
typeof id_institucion === 'number'
? await this.institucionService.findById(id_institucion)
: id_institucion;
2022-04-18 16:55:19 -05:00
return this.repository
2022-05-02 15:50:00 -05:00
.findOne({ institucion, modulo })
.then((existeModulo) => {
if (existeModulo)
throw new ConflictException(
'Ya existe un módulo con este nombre, intente con otro nombre.',
);
2022-05-02 15:50:00 -05:00
});
2022-04-04 20:02:54 -05:00
}
2022-04-16 13:05:27 -05:00
2022-04-16 14:37:17 -05:00
findAll() {
2022-04-18 16:55:19 -05:00
return this.repository.find();
2022-04-16 14:37:17 -05:00
}
findAllByIdInstitucion(id_institucion: number) {
return this.institucionService
.findById(id_institucion)
2022-04-18 16:55:19 -05:00
.then((institucion) => this.repository.find({ institucion }));
2022-04-16 14:37:17 -05:00
}
findById(id_modulo: number) {
2022-04-18 16:55:19 -05:00
return this.repository.findOne({ id_modulo }).then((modulo) => {
2022-04-16 14:37:17 -05:00
if (!modulo) throw new NotFoundException('No existe este módulo.');
return modulo;
});
}
2022-04-21 22:08:59 -05:00
update(attrs: Partial<Modulo>) {
return this.findById(attrs.id_modulo)
.then(async (modulo) => {
if (attrs.modulo)
2022-05-02 15:50:00 -05:00
await this.existeModulo(modulo.institucion, attrs.modulo);
2022-04-16 13:05:27 -05:00
Object.assign(modulo, attrs);
2022-04-18 16:55:19 -05:00
return this.repository.save(modulo);
2022-04-16 13:07:55 -05:00
})
2022-04-18 16:55:19 -05:00
.then((_) => ({
2022-04-16 13:07:55 -05:00
message: 'Se actualizo correctamente la información del módulo.',
}));
2022-04-16 13:05:27 -05:00
}
2022-04-04 20:02:54 -05:00
}