ppob-backend/src/product/product-categories.service.ts

137 lines
3.3 KiB
TypeScript

import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { EntityNotFoundError, Repository } from 'typeorm';
import { ProductCategories } from './entities/product-category.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { CreateCategoriesProductDto } from './dto/categories/create-categories-product.dto';
import { UpdateCategoriesProductDto } from './dto/categories/update-categories-product.dto';
@Injectable()
export class ProductCategoriesService {
constructor(
@InjectRepository(ProductCategories)
private productCategoriesRepository: Repository<ProductCategories>,
) {}
async create(CreateCategoriesProductDto: CreateCategoriesProductDto) {
const check = await this.productCategoriesRepository.findOne({
code: CreateCategoriesProductDto.code,
});
if (check) {
throw new HttpException(
{
statusCode: HttpStatus.NOT_ACCEPTABLE,
error: 'Category Already Exist',
},
HttpStatus.NOT_FOUND,
);
}
const result = await this.productCategoriesRepository.insert(
CreateCategoriesProductDto,
);
return this.productCategoriesRepository.findOneOrFail(
result.identifiers[0].id,
);
}
findAll(page) {
return this.productCategoriesRepository.findAndCount({
skip: page * 10,
take: 10,
order: {
version: 'DESC',
},
});
}
async findOne(id: string) {
try {
return await this.productCategoriesRepository.findOneOrFail(id);
} catch (e) {
if (e instanceof EntityNotFoundError) {
throw new HttpException(
{
statusCode: HttpStatus.NOT_FOUND,
error: 'Data not found',
},
HttpStatus.NOT_FOUND,
);
} else {
throw e;
}
}
}
async findByCode(code: string) {
try {
return await this.productCategoriesRepository.findOneOrFail({
where: {
code: code,
},
});
} catch (e) {
if (e instanceof EntityNotFoundError) {
throw new HttpException(
{
statusCode: HttpStatus.NOT_FOUND,
error: 'Data not found',
},
HttpStatus.NOT_FOUND,
);
} else {
throw e;
}
}
}
async update(
id: string,
updateCategoriesProductDto: UpdateCategoriesProductDto,
) {
try {
await this.productCategoriesRepository.findOneOrFail(id);
} catch (e) {
if (e instanceof EntityNotFoundError) {
throw new HttpException(
{
statusCode: HttpStatus.NOT_FOUND,
error: 'Data not found',
},
HttpStatus.NOT_FOUND,
);
} else {
throw e;
}
}
const result = await this.productCategoriesRepository.update(
id,
updateCategoriesProductDto,
);
return this.productCategoriesRepository.findOneOrFail(id);
}
async remove(id: string) {
try {
await this.productCategoriesRepository.findOneOrFail(id);
} catch (e) {
if (e instanceof EntityNotFoundError) {
throw new HttpException(
{
statusCode: HttpStatus.NOT_FOUND,
error: 'Data not found',
},
HttpStatus.NOT_FOUND,
);
} else {
throw e;
}
}
await this.productCategoriesRepository.delete(id);
}
}