80 lines
2.3 KiB
TypeScript
80 lines
2.3 KiB
TypeScript
import {
|
|
ConflictException,
|
|
Injectable,
|
|
NotFoundException,
|
|
} from '@nestjs/common';
|
|
import { InjectRepository } from '@nestjs/typeorm';
|
|
import { Repository } from 'typeorm';
|
|
import { Institucion } from 'src/institucion/entity/institucion.entity';
|
|
import { Modulo } from './entity/modulo.entity';
|
|
import { InstitucionService } from '../institucion/institucion.service';
|
|
|
|
@Injectable()
|
|
export class ModuloService {
|
|
constructor(
|
|
@InjectRepository(Modulo) private repository: Repository<Modulo>,
|
|
private institucionService: InstitucionService,
|
|
) {}
|
|
|
|
async create(id_institucion: number, modulo: string) {
|
|
const institucion = await this.institucionService.findById(id_institucion);
|
|
|
|
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;
|
|
|
|
return this.repository
|
|
.findOne({ institucion, modulo })
|
|
.then((existeModulo) => {
|
|
if (existeModulo)
|
|
throw new ConflictException(
|
|
'Ya existe un módulo con este nombre, intente con otro nombre.',
|
|
);
|
|
});
|
|
}
|
|
|
|
findAll() {
|
|
return this.repository.find();
|
|
}
|
|
|
|
findAllByIdInstitucion(id_institucion: number) {
|
|
return this.institucionService
|
|
.findById(id_institucion)
|
|
.then((institucion) => this.repository.find({ institucion }));
|
|
}
|
|
|
|
findById(id_modulo: number) {
|
|
return this.repository.findOne({ id_modulo }).then((modulo) => {
|
|
if (!modulo) throw new NotFoundException('No existe este módulo.');
|
|
return modulo;
|
|
});
|
|
}
|
|
|
|
update(attrs: Partial<Modulo>) {
|
|
return this.findById(attrs.id_modulo)
|
|
.then(async (modulo) => {
|
|
if (attrs.modulo)
|
|
await this.existeModulo(modulo.institucion, attrs.modulo);
|
|
Object.assign(modulo, attrs);
|
|
return this.repository.save(modulo);
|
|
})
|
|
.then((_) => ({
|
|
message: 'Se actualizo correctamente la información del módulo.',
|
|
}));
|
|
}
|
|
}
|