ppob-backend/src/product/product-sub-categories.service.ts
2021-12-06 22:31:22 +07:00

112 lines
3.1 KiB
TypeScript

import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { EntityNotFoundError, Repository } from 'typeorm';
import { ProductSubCategories } from './entities/product-sub-category.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { CreateSubCategoriesProductDto } from './dto/sub-categories/create-sub-categories-product.dto';
import { UpdateSubCategoriesProductDto } from './dto/sub-categories/update-sub-categories-product.dto';
import { ProductCategoriesService } from './product-categories.service';
@Injectable()
export class ProductSubCategoriesService {
constructor(
@InjectRepository(ProductSubCategories)
private productSubCategoriesRepository: Repository<ProductSubCategories>,
private productCategoriesService: ProductCategoriesService,
) {}
async create(createSubCategoriesProductDto: CreateSubCategoriesProductDto) {
const categories = await this.productCategoriesService.findOne(
createSubCategoriesProductDto.categoryId,
);
const result = await this.productSubCategoriesRepository.insert({
name: createSubCategoriesProductDto.name,
category: categories,
});
return this.productSubCategoriesRepository.findOneOrFail(
result.identifiers[0].id,
);
}
findAll(page) {
return this.productSubCategoriesRepository.findAndCount({
skip: page * 10,
take: 10,
order: {
version: 'DESC',
},
});
}
async findOne(id: string) {
try {
return await this.productSubCategoriesRepository.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 update(
id: string,
updateCategoriesProductDto: UpdateSubCategoriesProductDto,
) {
try {
await this.productSubCategoriesRepository.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 categories = await this.productCategoriesService.findOne(
updateCategoriesProductDto.categoryId,
);
const result = await this.productSubCategoriesRepository.update(id, {
name: updateCategoriesProductDto.name,
category: categories,
});
return this.productSubCategoriesRepository.findOneOrFail(id);
}
async remove(id: string) {
try {
await this.productSubCategoriesRepository.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.productSubCategoriesRepository.delete(id);
}
}