All files / src/repositories feature.repository.ts

44.44% Statements 12/27
0% Branches 0/6
25% Functions 1/4
40% Lines 10/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 631x 1x 1x 1x 1x 1x     1x                         18x   18x 18x                                                                            
import {Getter, inject} from '@loopback/core';
import {BelongsToAccessor, repository} from '@loopback/repository';
import {LogChainDataSource} from '../datasources';
import {Feature, FeatureRelations, Module} from '../models';
import {ErrorUtils, ValidationError} from '../utils/error';
import {BaseCrudRepository} from './base-crud.repository.base';
import {ModuleRepository} from './module.repository';
 
export class FeatureRepository extends BaseCrudRepository<
  Feature,
  typeof Feature.prototype.id,
  FeatureRelations
> {
  public readonly module: BelongsToAccessor<
    Module,
    typeof Feature.prototype.id
  >;
 
  constructor(
    @inject('datasources.logchain') dataSource: LogChainDataSource,
    @repository.getter('ModuleRepository')
    protected moduleRepositoryGetter: Getter<ModuleRepository>,
  ) {
    super(Feature, dataSource);
    this.module = this.createBelongsToAccessor('module', moduleRepositoryGetter);
  }
 
  /**
   * Ensure all country is active
   * @param ids The array id of Country
   * @returns A promise
   */
  async ensureRecordActive(ids: Array<number>): Promise<void | Error> {
    const model_name = this.modelClass.modelName;
    if (!ids.length) {
      throw new Error(`${model_name} is empty`);
    }
 
    const pTasks: Promise<void | Error>[] = [];
 
    ids.forEach((id, idx) => {
      pTasks[idx] = (async () => {
        const {count} = await this.count({
          id: id,
          status: true,
        });
        if (!count) {
          throw new Error(`${model_name} ${id} is not active or not exists.`);
        }
      })();
    });
    const resl = await Promise.allSettled(pTasks);
    if (ErrorUtils.hasError(resl)) {
      const err = new ValidationError(
        `Please ensure the ${model_name} is active.`,
      );
      err.statusCode = 400;
      err.details = ErrorUtils.buildErrorDetails(resl);
      throw err;
    }
  }
}