44 lines
1.5 KiB
TypeScript
44 lines
1.5 KiB
TypeScript
import { ConflictException, Injectable } from '@nestjs/common';
|
|
import { InjectRepository } from '@nestjs/typeorm';
|
|
import { Repository } from 'typeorm';
|
|
import { Marca } from './entity/marca.entity';
|
|
|
|
@Injectable()
|
|
export class MarcaService {
|
|
constructor(@InjectRepository(Marca) private repository: Repository<Marca>) {}
|
|
|
|
create(marca: string, tipo: string) {
|
|
// Buscamos una marca con ese nombre
|
|
return this.findByMarca(marca, tipo, false)
|
|
.then((existeMarca) => {
|
|
// Sacamos error si existe
|
|
if (existeMarca) throw new ConflictException('Ya existe esta marca.');
|
|
// Creamos y guardamos un registro
|
|
return this.repository.save(this.repository.create({ marca, tipo }));
|
|
})
|
|
.then((_) => ({ message: 'Se creó correctamente una nueva marca.' }));
|
|
}
|
|
|
|
findAll(tipo: string) {
|
|
return this.repository.find({ where: { tipo }, order: { tipo: 'ASC' } });
|
|
}
|
|
|
|
findById(id_marca: number, tipo: string, validarExistencia = true) {
|
|
return this.repository
|
|
.findOne({ where: { id_marca, tipo } })
|
|
.then((marca) => {
|
|
if (validarExistencia && !marca)
|
|
throw new ConflictException('No existe esta marca.');
|
|
return marca;
|
|
});
|
|
}
|
|
|
|
findByMarca(marca: string, tipo: string, validarExistencia = true) {
|
|
return this.repository.findOne({ where: { marca, tipo } }).then((marca) => {
|
|
if (validarExistencia && !marca)
|
|
throw new ConflictException('No existe esta marca.');
|
|
return marca;
|
|
});
|
|
}
|
|
}
|