pos-be/src/core/helpers/validation/validate-relation.helper.ts

44 lines
1.4 KiB
TypeScript

import { Injectable, UnprocessableEntityException } from '@nestjs/common';
import { BaseDataService } from 'src/core/modules/data/service/base-data.service';
import { validateRelations } from 'src/core/strings/constants/interface.constants';
@Injectable()
export class ValidateRelationHelper<Entity> {
constructor(
private dataId: string,
private dataService: BaseDataService<Entity>,
private relations: validateRelations[],
private tableName: string,
) {}
async execute() {
const repository = this.dataService.getRepository();
const queryBuilder = repository.createQueryBuilder(this.tableName);
// load relation
for (const relation of this.relations) {
queryBuilder.loadRelationCountAndMap(
`${this.tableName}.total_${relation.relation}`,
`${this.tableName}.${relation.relation}`,
`total_${relation.relation}`,
);
}
// filtering data only with specific data
queryBuilder.where(`${this.tableName}.id in ('${this.dataId}')`);
// get data
const data = await queryBuilder.getOne();
// process validasi
for (const relation of this.relations) {
const message =
relation.message ??
`Failed! this data already connected to ${relation.relation}`;
if (data[`total_${relation.relation}`])
throw new UnprocessableEntityException(message);
}
}
}