All files / src/repositories base-crud.repository.base.ts

52.55% Statements 72/137
48.39% Branches 60/124
53.85% Functions 14/26
53.33% Lines 72/135

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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 4901x 1x                                   1x 1x 1x 1x 1x           1x 1x 1x 1x 1x 1x   1x 1x         1x           1x     1x     1x     1x     1x     1x               3439x                 1x 1x   1x 1x       1x                                                                   1x         1x 1x 1x           1x                         1x     1x 1x                                                                   15x 15x                                                     27x 27x   27x 10x     17x 17x         17x             17x                       25x   25x           20x     25x           20x     25x 15x           6x       25x                                                                                             1x 1x                                                                                   1x 1x   1x 1x 1x   1x 1x 1x                             1x         1x     1x                                                                                                                                             20x                         6726x 6726x   6726x      
import { Getter, inject } from '@loopback/core';
import {
  AnyObject,
  BelongsToAccessor,
  Condition,
  DataObject,
  DefaultCrudRepository,
  DefaultTransactionalRepository,
  Entity,
  EntityCrudRepository,
  EntityNotFoundError,
  Filter,
  FilterBuilder,
  FilterExcludingWhere,
  InclusionResolver,
  juggler,
  Options,
  Where,
} from '@loopback/repository';
import { HttpErrors } from '@loopback/rest';
import { SecurityBindings } from '@loopback/security';
import { isEmpty } from 'lodash';
import { AwsServiceBindings } from '../components/aws/keys';
import {
  AwsCognitoService,
  AwsS3Service,
  AwsSesService,
  UserProfile,
} from '../components/aws/services';
import { CAService, CCService } from '../components/fabric';
import { FabricServiceBindings } from '../components/fabric/keys';
import { Constants } from '../configs';
import * as models from '../models';
import { BaseEntity, EntryRecord } from '../models';
import { Status as StatusModel } from '../models/status';
import { Created, Modified, Status } from '../types';
import { FindSubRepository } from '../utils/findsub.repository';
import { EntityNotActiveError } from './errors';
import { Target as AwsTarget } from 'aws-sdk/clients/cloudwatchevents';
 
interface Target extends Entity, AwsTarget {}
 
export class BaseCrudRepository<
  T extends BaseEntity,
  ID,
  Relations extends object = {}
  > extends DefaultTransactionalRepository<T, ID, Relations> {
  @inject(SecurityBindings.USER, { optional: true })
  public current_user?: UserProfile;
 
  @inject(AwsServiceBindings.S3_SERVICE)
  public s3_service: AwsS3Service;
 
  @inject(AwsServiceBindings.COGNITO_SERVICE)
  public cognito_service: AwsCognitoService;
 
  @inject(AwsServiceBindings.SES_SERVICE)
  public ses_service: AwsSesService;
 
  @inject(FabricServiceBindings.CA_SERVICE)
  public ca_service: CAService;
 
  @inject(FabricServiceBindings.CC_SERVICE)
  public cc_service: CCService;
 
  constructor(
    entityClass: typeof Entity & {
      prototype: T;
    },
    dataSource: juggler.DataSource,
  ) {
    super(entityClass, dataSource);
  }
 
  /**
   * Find with paging.
   * @param filter
   * @param options
   */
  async findWithPaging(filter: Filter<T>, options?: Options) {
    const { offset = 0, limit = Constants.DefaultLimit, where = {} } = filter;
    this.checkOrderFilter(filter?.order);
 
    filter.where = this.rebuildWhere(where);
    const [total, data] = await Promise.all([
      super.count(filter?.where, options),
      super.find(filter, options),
    ]);
    return {
      total: total.count,
      has_more: total.count > offset + limit,
      data,
    };
  }
 
  /**
   * Re-Build where clause.
   * @example
   * From
   * ```
   * {
   *   name: {inq: ['John', 'Mary']},
   *   status: 'ACTIVE'
   *   and: [...],
   *   or: [...],
   * }
   * ```
   * to
   * ```
   * {
   *   and: [
   *     {name: {inq: ['John', 'Mary']}},
   *     {status: 'ACTIVE'}
   *     {and: [...]}
   *     {or: [...]}
   *   ]
   * }
   * ```
   * @param where The where clause
   * @returns New where clause.
   */
  protected rebuildWhere(where: {}) {
    Iif (isEmpty(where)) {
      return where;
    }
 
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const _w: { and: any[] } = { and: [] };
    Object.keys(where).forEach(key => {
      _w.and.push({
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        [`${key}`]: (where as { [x: string]: any })[key],
      });
    });
 
    return _w;
  }
 
  /**
   * Create or update a record.
   * @param filter The filter.
   * @param entity The entity data to create.
   */
  async upsertWithWhere(
    where: Where<T>,
    entity: DataObject<T>,
    options: Options = {},
  ) {
    const { count } = await super.updateAll(entity, where, options);
 
    // create new if it doesn't exist'
    Eif (!count) {
      return this.create(entity, options);
    } else {
      if (options?.returnInstanceAfterUpdate) {
        return this.findOne({ where }, options);
      }
    }
  }
 
  /**
   * Find or update a record.
   * @param filter The filter.
   * @param entity The entity data to create.
   */
  async findOrCreate(
    where: Where<T>,
    entity: DataObject<T>,
    options: Options = {},
  ) {
    const inst = await super.findOne({ where }, options);
 
    // create new if it doesn't exist'
    if (!inst) {
      return this.create(entity, options);
    }
 
    return inst;
  }
 
  /**
   * Override create to set is_create: true
   * @param entity The entity
   * @param options The options
   */
  async create(entity: DataObject<T>, options: Options = {}): Promise<T> {
    options.is_create = true;
    return super.create(entity, options);
  }
 
  /**
   * Override createAll to set is_create: true
   * @param entity The entities
   * @param options The options
   */
  async createAll(
    entities: DataObject<T>[],
    options: Options = {},
  ): Promise<T[]> {
    options.is_create = true;
    return super.createAll(entities, options);
  }
 
  /**
   * Override findOne to get ref_documents for some models
   * (bol, document, eir, entry, loading, reheating, transport, weighbridge).
   * @param filter The filter object.
   * @param options The options.
   * @param [options.get_reference] The flag to get ref documents.
   */
  async findOne(
    filter?: Filter<T>,
    options?: Options,
  ): Promise<(T & Relations) | null> {
    options = { maxDepthOfQuery: Number.MAX_SAFE_INTEGER, ...options ?? {} };
    const inst = await super.findOne(filter, options);
 
    if (!inst) {
      return null;
    }
 
    let { flow_id, journey_point_id } = inst as AnyObject;
    Iif (inst instanceof EntryRecord) {
      const { entry } = inst as EntryRecord;
      flow_id = entry?.flow_id;
      journey_point_id = entry?.journey_point_id;
    }
    Iif (flow_id && journey_point_id && options?.get_reference) {
      (inst as AnyObject).ref_documents = await this.execute(
        'SELECT * FROM get_reference_documents($1, $2);',
        [flow_id, journey_point_id],
      );
    }
 
    return inst;
  }
 
  /**
   * Override entityToData to update `modified_date` and `modified_by`
   * @param entity The entity passed from CRUD operations' caller.
   * @param options
   */
  async entityToData<R extends T>(
    entity: R | DataObject<R>,
    options?: { is_create: boolean },
  ) {
    const data = await super.entityToData(entity, options);
 
    if (
      Object.prototype.hasOwnProperty.call(
        this.modelClass.definition.properties,
        'modified_date',
      )
    ) {
      (data as Modified).modified_date = new Date();
    }
 
    if (
      Object.prototype.hasOwnProperty.call(
        this.modelClass.definition.properties,
        'modified_by',
      )
    ) {
      (data as Modified).modified_by = this.current_user?.id;
    }
 
    if (options?.is_create) {
      if (
        Object.prototype.hasOwnProperty.call(
          this.modelClass.definition.properties,
          'created_by',
        )
      ) {
        (data as Created).created_by = this.current_user?.id;
      }
    }
 
    return data;
  }
  
  /**
   * Find one record with status is active.
   * @param id The entity id.
   * @param filter The filter object.
   * @param options The options object.
   */
  async findByIdWithActiveStatus(
    id: ID | string,
    filter?: FilterExcludingWhere<T>,
    options?: Options,
  ): Promise<T & Relations> {
    let result: T & Relations;
 
    if (typeof id === 'number') {
      result = await super.findById(id, filter, options);
    } else {
      result = await super.findOne(
        {
          where: {
            identifier: id,
          } as Condition<T>,
        },
        options,
      ) ?? {} as T & Relations;
    }
 
    if (!result) {
      throw new EntityNotFoundError(this.entityClass, id);
    }
 
    const status = (result as Status).status;
 
    if (status !== true && status !== (StatusModel as { [key: string]: { [key: string]: number | string } })[this.modelClass.name].Active) {
      throw new EntityNotActiveError(this.entityClass, id);
    }
 
    return result;
  }
 
  /**
   * Checks if the order filter is valid
   * @param order The order of query entity
   */
  checkOrderFilter(order?: string[]) {
    Eif (!order || !order.length) {
      return;
    }
 
    for (const op of order) {
      if (!this.isValidOrderFilter(op, this.entityClass.definition.properties)) {
        throw new HttpErrors.BadRequest(
          `${op} is not a valid order filter for ${this.entityClass.modelName}`,
        );
      }
    }
  }
 
  /**
   * Checks if the order filter is valid
   * @param orderFilter The order filter to check
   * @param properties The properties of the entity
   * @returns True if the order filter is valid, false otherwise
   */
  private isValidOrderFilter(orderFilter: string, properties: { [key: string]: any }): boolean {
    const [fieldName] = orderFilter.split(' ');
 
    if (!Object.prototype.hasOwnProperty.call(properties, fieldName)) {
      return false;
    }
 
    return true;
  }
 
  /**
   * Asynchronously processes and fills relations for a given filter condition.
   * The function traverses and modifies the filter conditions to ensure that
   * related entities are properly included in the query.
   * 
   * @param filterBuilder - The filter builder instance used to construct the query filter.
   * @param options - Additional options that may influence the query execution.
   * 
   * This function handles complex conditions such as 'and'/'or' logic by
   * rebuilding the query structure to include model relations. It uses
   * asynchronous tasks to efficiently process each condition and ensures all
   * tasks are settled before retrieving the paginated results.
   */
  async fillRelation(filterBuilder: FilterBuilder, options: Options = {}) {
    const _models: any = models;
    const where: any = filterBuilder.build()?.where;
 
    const ctask: Promise<void>[] = [];
    const ptask: Promise<void>[] = [];
    const ktask: Promise<void>[] = [];
 
    Object.keys(where).map((x, idx_where) => {
      ktask[idx_where] = (async () => {
        Iif (x === 'or' || x === 'and') {
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          where[x].map(async (el: any, idx_or_and: number) => {
            ptask[idx_or_and] = (async () => {
              // eslint-disable-next-line @typescript-eslint/no-explicit-any
              Object.keys(el).map((key: any, idx: number) => {
                ctask[idx] = (async () => {
                  await this.rebuildBuilder(el, key, _models);
                })();
              });
              await Promise.allSettled(ctask);
            })();
          });
          await Promise.allSettled(ptask);
        }
        Iif (x.indexOf('.') !== -1) {
          await this.rebuildBuilder(where, x, _models);
        }
      })();
    });
    await Promise.allSettled(ktask);
 
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    return this.findWithPaging(filterBuilder.build() as any, options);
  }
 
  /**
   * Returns the target model name of relation if exists.
   * @param key - The relation key.
   * @returns The target model name if exists, otherwise empty string.
   */
  getModelName(key: string | undefined): string {
    if (key) {
      const target_model = this.entityClass.definition.relations[key];
      if (target_model) {
        const target_model_name = target_model.target.toString().split('.')[
          target_model.target.toString().split('.').length - 1
        ];
        return target_model_name;
      }
    }
 
    return '';
  }
 
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  private async rebuildBuilder(where: any, key: any, _models: any) {
    const list_key = key.split('.');
    const modelName = this.getModelName(list_key[0]);
    if (!modelName) {
      return;
    }
    const repo = new FindSubRepository(_models[modelName], this.dataSource);
    const condition: any = {};
    condition[list_key[1]] = where[key];
    const res = await repo.findSubRepo({
      where: condition,
    });
    if (res.length) {
      where[`${list_key[0]}_id`] = {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        inq: res.map((re: any) => re.id),
      };
    } else {
      where[`${list_key[0]}_id`] = null;
    }
  }
 
  /**
   *
   * @param field The field name.
   * @param values The values.
   */
  public buildInClause(field: string, values: unknown[], start = 1) {
    const separator = ',';
    const dollar = '$';
    let sql = `${field} IN (`;
    for (let i = 0, n = values.length; i < n; i++) {
      sql += dollar + (i + start);
 
      if (i < n - 1) {
        sql += separator;
      }
    }
    return sql + ')';
  }
 
  /**
   * @method
   * @description Get the postgres table name
   * @name getPostgresTableName
   * @return {string}
   */
  public getPostgresTableName(): string {
    return this.entityClass.definition.settings?.postgresql?.table || '';
  }
 
  /**
   * Creates a belongsTo accessor for the given related model.
   * @param relatedRepoGetter The getter for the related model's repository.
   * @returns A belongsTo accessor.
   */
  // eslint-disable-next-line @typescript-eslint/no-shadow
  createBelongsToAccessor<Target extends Entity, TargetId>(
    propertyName: string,
    relatedRepoGetter: Getter<EntityCrudRepository<Target, TargetId>>
  ): BelongsToAccessor<Target, ID> {
    const repo = this.createBelongsToAccessorFor(propertyName, relatedRepoGetter);
    this.registerInclusionResolver(propertyName, repo.inclusionResolver);
 
    return repo;
  }
}