All files / src/controllers base-crud.controller.ts

52.48% Statements 53/101
11.93% Branches 13/109
47.62% Functions 10/21
52.48% Lines 53/101

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 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 6801x 1x   1x     1x 1x   1x       1x 1x   1x                                                                                                     1x                                                                           1x           1x     1x     1x     2x 2x                                                                                                                                                               12x                                                         12x                                                       12x                       34x                                         34x                                 34x                       28x             28x                                               28x                       28x                       25x                 25x                                 25x                                                                   25x                       12x             12x                           12x                               12x                     1x             1x                                             1x                     1x                     1x             1x                               1x                                                             1x                     1x             1x                           1x                                       1x     1x 39x   39x                   39x 114x 114x       39x        
import { authorize } from '@loopback/authorization';
import { inject, intercept, MixinTarget, service } from '@loopback/core';
import { Model, Options, Where } from '@loopback/repository';
import {
  del, get, getWhereSchemaFor, param, patch, post, Request, requestBody, RestBindings,
} from '@loopback/rest';
import { SecurityBindings } from '@loopback/security';
import { cloneDeep, merge } from 'lodash';
 
import {
  buildResponseObject, buildResponseObjectById, getModelSchemaRefWithoutAutoPopulate, limitSpec, offsetSpec, qSpec, sortSpec,
} from '@logchain/apidefs';
import { UserProfile } from '@logchain/components/aws';
import { Module, Constants, CONTENT_TYPE } from '@logchain/configs';
import { EnsurePagingCorrectInterceptor, EnsureProvideDataInterceptor, serialize, } from '@logchain/interceptors';
import { BaseEntity, BaseResponses } from '@logchain/models';
import { AuditLogService, BaseService } from '@logchain/services';
import { AnyObject, StringFormat } from '@logchain/types';
import {
  ICreate, IRead, IReadById, IUpdateById, IDeleteId, IReadByIdentifier, IUpdateByIdentifier, IDeleteByIdentifier
} from '@logchain/mixins';
 
/**
 * Options to mix in controller
 */
export interface MixinOptions {
  /**
   * Base path for the controller
   */
  basePath: string;
  /**
   * Model class for CRUD
   */
  modelClass: typeof Model;
 
  /**
   * Model DTO class for CRUD
   */
  modelDtoClass: typeof Model;
 
  /**
   * private or public api
   */
  admin?: boolean;
 
  /**
   * Excludes fields for `requestBody`
   */
  schemaOptions: {
    [property: string]: Options;
  };
}
 
export interface ExtendOptions {
  isExtendCreate?: boolean;
  isExtendRead?: boolean;
  isExtendReadById?: boolean;
  isExtendUpdateById?: boolean;
  isExtendDeleteById?: boolean;
  isExtendReadByIdentifier?: boolean;
  isExtendUpdateByIdentifier?: boolean;
  isExtendDeleteByIdentifier?: boolean;
}
 
/**
 * Default acls for CRUD
 */
const DEFAULT_ACL = {
  schemaOptions: {
    create: {
      authorize: {
        resource: Module.Public,
      },
    },
    updateById: {
      authorize: {
        resource: Module.Public,
      },
    },
    updateByIdentifier: {
      authorize: {
        resource: Module.Public,
      },
    },
    deleteById: {
      authorize: {
        resource: Module.Public,
      },
    },
    findById: {
      authorize: {
        resource: Module.Public,
      },
    },
    find: {
      authorize: {
        resource: Module.Public,
      },
    },
  },
};
 
/**
 * Base controller
 */
export class BaseController {
  public readonly is_private: boolean;
 
  public readonly is_default_flow: boolean;
 
  @service()
  public log_service: AuditLogService;
 
  @inject(RestBindings.Http.REQUEST)
  public req: Request;
 
  @inject(SecurityBindings.USER, { optional: true })
  public current_user: UserProfile;
 
  constructor() {
    this.is_private = this.constructor.name.indexOf(Constants.ApiRealm.Private) > -1;
    this.is_default_flow = this.constructor.name.indexOf('Default') > -1;
  }
 
  /**
   * Write log function
   * @param model_class
   * @param entity_id
   * @param data
   */
  public writeLog(
    model_class: typeof Model,
    entity_id?: number | string,
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    data?: any,
    template?: StringFormat,
    action = '',
    resource_name = '',
  ) {
    action = this._convertMethodToAction(action || this.req.method);
    // eslint-disable-next-line @typescript-eslint/no-misused-promises
    setImmediate(async () => {
      let name = '';
 
      if (data) {
        if (Object.prototype.hasOwnProperty.call(data, 'name')) {
          name = data.name;
        }
 
        // for case is bol
        if (Object.prototype.hasOwnProperty.call(data, 'bol_no')) {
          name = data.bol_no;
        }
 
        // for case is weighbridges
        if (Object.prototype.hasOwnProperty.call(data, 'ticket_no')) {
          name = data.ticket_no;
        }
      }
 
      await this.log_service.writeActivity({
        action,
        model_class,
        resource_name: resource_name ? resource_name : model_class.modelName,
        entity_id,
        template: template ?? {
          str: '{2}',
          args: [name],
        },
      });
    });
  }
 
  /**
   * Convert http method to action
   * @param method Then http method
   */
  private _convertMethodToAction(method: string): string {
    switch (method) {
      case 'POST':
        return 'Create';
      case 'DELETE':
        return 'Delete';
      case 'PATCH':
      case 'PUT':
        return 'Update';
      default:
        return method;
    }
  }
}
 
/**
 * A mixin factory for controllers to extend Create
 * @param superClass - Base class
 * @param options - Options for the controller
 *
 * @typeParam M - Model class
 * @typeParam T - Base class
 */
function createCtlMixin<M extends BaseEntity, T extends MixinTarget<BaseController>>(superClass: T, options: Options) {
  options = merge(cloneDeep(DEFAULT_ACL), options);
 
  class BaseCreateController extends superClass implements ICreate<M> {
    // Value will be provided by the subclassed controller class
    selfService: BaseService<M>;
 
    /**
     * Create a new model instance
     * @param model The info to create
     * @returns The ID of new instance
     */
    @post(`${options.basePath}`, {
      responses: {
        '200': {
          description: `The ID of new ${options.modelClass.modelName}`,
          content: {
            [CONTENT_TYPE.JSON]: {
              schema: {
                type: 'object',
                properties: {
                  id: { type: 'number' },
                },
              },
            },
          },
        },
      },
    })
    @authorize(options.schemaOptions['create'].authorize)
    async create(
      @requestBody({
        content: {
          [CONTENT_TYPE.JSON]: {
            schema: options.schemaOptions['create'].jsonSchema || getModelSchemaRefWithoutAutoPopulate(
              options.modelDtoClass,
              {
                title:
                  options.schemaOptions['create']?.title ||
                  `New${options.modelClass.modelName}`,
                exclude: options.schemaOptions['create']?.exclude,
              },
            ),
          },
        },
      })
      model: Pick<M, Exclude<keyof M, 'id'>>,
    ): Promise<{ id: number | undefined; identifier?: string | undefined }> {
      const created_inst = await this.selfService.create(model, {
        is_default_flow: this.is_default_flow,
      });
      const { id, identifier, activity } = created_inst;
      const action = activity?.args?.length ? activity.args[0] as string : undefined;
      this.writeLog(options.modelClass, id, model, activity, action);
 
      return options?.admin ? created_inst : { id, identifier };
    }
  }
  return BaseCreateController;
}
 
/**
 * A mixin factory for controllers to extend Read
 * @param superClass - Base class
 * @param options - Options for the controller
 *
 * @typeParam M - Model class
 * @typeParam T - Base class
 */
function readCtlMixin<M extends BaseEntity, T extends MixinTarget<BaseController>>(superClass: T, options: Options) {
  options = merge(cloneDeep(DEFAULT_ACL), options);
 
  class BaseReadController extends superClass implements IRead<M> {
    // Value will be provided by the subclassed controller class
    selfService: BaseService<M>;
 
    /**
     * Find list of `modelClass` based on query
     * @param offset The offset number
     * @param limit The limit number
     * @param sort The array order
     * @param where The query object
     */
    @get(`${options.basePath}`, {
      responses: {
        '200': buildResponseObject(options.modelDtoClass, options.admin),
      },
    })
    @intercept(EnsurePagingCorrectInterceptor.BINDING_KEY)
    @authorize(options.schemaOptions['find'].authorize)
    @intercept(serialize(options.modelDtoClass))
    async find(
      @param(offsetSpec) offset: number,
      @param(limitSpec) limit: number,
      @param(sortSpec) sort: Array<string>,
      @param(qSpec) q: string,
      @param.query.object('where', getWhereSchemaFor(options.modelClass))
      where: Where<M>,
    ): Promise<BaseResponses<M>> {
      this.selfService.buildBaseFilter(offset, limit, sort, where);
      await this.selfService.buildSearchQuery(q);
 
      if (!this.is_private) {
        this.selfService.ensureRightAccessRecord();
      }
      return this.selfService.find({ is_private: this.is_private });
    }
  }
  return BaseReadController;
}
 
/**
 * A mixin factory for controllers to extend RUD by ID
 * @param superClass - Base class
 * @param options - Options for the controller
 *
 * @typeParam M - Model class
 * @typeParam T - Base class
 */
function readByIdCtlMixin<M extends BaseEntity, T extends MixinTarget<BaseController>>(superClass: T, options: Options) {
  options = merge(cloneDeep(DEFAULT_ACL), options);
 
  class BaseReadByIdController extends superClass implements IReadById<M> {
    // Value will be provided by the subclassed controller class
    selfService: BaseService<M>;
 
    @service()
    public log_service: AuditLogService;
 
    /**
     * Get model instance by id
     * @param id The ID of model
     * @returns Model instance
     */
    @get(`/${options.basePath}/{id}`, {
      responses: {
        '200': {
          description: `${options.modelClass.modelName} model instance`,
          content: {
            [CONTENT_TYPE.JSON]: {
              schema: buildResponseObjectById(
                options.modelDtoClass,
                options.admin,
              ),
            },
          },
        },
      },
    })
    @authorize(options.schemaOptions['findById'].authorize)
    @intercept(serialize(options.modelDtoClass))
    async findById(
      @param.path.integer('id') id: number,
    ): Promise<M | AnyObject> {
      if (!this.is_private) {
        this.selfService.ensureRightAccessRecord();
      }
      return this.selfService.getByIdOrIdentifier(id, {
        is_private: this.is_private,
      });
    }
  }
 
  return BaseReadByIdController;
}
 
/**
 * A mixin factory for controllers to extend RUD by ID
 * @param superClass - Base class
 * @param options - Options for the controller
 *
 * @typeParam M - Model class
 * @typeParam T - Base class
 */
function updateByIdCtlMixin<M extends BaseEntity, T extends MixinTarget<BaseController>>(superClass: T, options: Options) {
  options = merge(cloneDeep(DEFAULT_ACL), options);
 
  class BaseUpdateByIdController
    extends superClass
    implements IUpdateById<M> {
    // Value will be provided by the subclassed controller class
    selfService: BaseService<M>;
 
    @service()
    public log_service: AuditLogService;
 
    /**
     * Update model instance by id
     * @param id The ID of model
     * @param model The new information of model
     * @returns Promise<void>
     */
    @patch(`/${options.basePath}/{id}`, {
      responses: {
        '204': {
          description: `${options.modelClass.modelName} PATCH success`,
        },
      },
    })
    @intercept(EnsureProvideDataInterceptor.BINDING_KEY)
    @authorize(options.schemaOptions['updateById'].authorize)
    async updateById(
      @param.path.integer('id') id: number,
      @requestBody({
        content: {
          [CONTENT_TYPE.JSON]: {
            schema: options.schemaOptions['updateById'].jsonSchema || getModelSchemaRefWithoutAutoPopulate(
              options.modelDtoClass,
              {
                partial: true,
                exclude: options.schemaOptions['updateById'].exclude,
              },
            ),
          },
        },
      })
      model: Partial<M>,
    ): Promise<void> {
      if (!this.is_private) {
        this.selfService.ensureRightAccessRecord();
      }
      const updated_inst = await this.selfService.updateByIdOrIdentifier(
        id,
        model,
        { is_private: this.is_private },
      );
      this.writeLog(
        options.modelClass,
        id,
        updated_inst,
        updated_inst?.activity,
        updated_inst?.activity ? updated_inst.activity.args[0] as string : undefined,
      );
    }
  }
  return BaseUpdateByIdController;
}
 
/**
 * A mixin factory for controllers to extend RUD by ID
 * @param superClass - Base class
 * @param options - Options for the controller
 *
 * @typeParam M - Model class
 * @typeParam T - Base class
 */
function deleteByIdCtlMixin<M extends BaseEntity, T extends MixinTarget<BaseController>>(superClass: T, options: Options) {
  options = merge(cloneDeep(DEFAULT_ACL), options);
 
  class BaseDeleteByIdController extends superClass implements IDeleteId {
    // Value will be provided by the subclassed controller class
    selfService: BaseService<M>;
 
    @service()
    public log_service: AuditLogService;
    /**
     * Delete model instance by id
     * @param id The model id
     * @returns Promise<void>
     */
    @del(`/${options.basePath}/{id}`, {
      responses: {
        '204': {
          description: `${options.modelClass.modelName} DELETE success`,
        },
      },
    })
    @authorize(options.schemaOptions['deleteById'].authorize)
    async deleteById(@param.path.integer('id') id: number): Promise<void> {
      if (!this.is_private) {
        this.selfService.ensureRightAccessRecord();
      }
      const deleted_inst = await this.selfService.deleteByIdOrIdentifier(id, {
        is_private: this.is_private,
      });
      this.writeLog(
        options.modelClass,
        id,
        deleted_inst,
        deleted_inst.activity,
        deleted_inst?.activity ? deleted_inst.activity.args[0] as string : undefined,
      );
    }
  }
  return BaseDeleteByIdController;
}
 
/**
 * A mixin factory for controllers to extend RUD by Identifier
 * @param superClass - Base class
 * @param options - Options for the controller
 * @typeParam M - Model class
 * @typeParam T - Base class
 */
function readByIdentifierCtlMixin<M extends BaseEntity, T extends MixinTarget<BaseController>>(superClass: T, options: Options) {
  options = merge(cloneDeep(DEFAULT_ACL), options);
 
  class BaseReadByIdentifierController extends superClass implements IReadByIdentifier<M> {
    // Value will be provided by the subclassed controller class
    selfService: BaseService<M>;
 
    @service()
    public log_service: AuditLogService;
 
    /**
     * Get model instance by identifier
     * @param identifier The identifier of model
     * @returns Model instance
     */
    @get(`/${options.basePath}/{identifier}`, {
      responses: {
        '200': {
          description: `${options.modelClass.modelName} model instance`,
          content: {
            [CONTENT_TYPE.JSON]: {
              schema: buildResponseObjectById(
                options.modelDtoClass,
                options.admin,
              ),
            },
          },
        },
      },
    })
    @intercept(serialize(options.modelDtoClass))
    findByIdentifier(
      @param.path.string('identifier') identifier: string,
    ): Promise<M | AnyObject> {
      if (!this.is_private) {
        this.selfService.ensureRightAccessRecord();
      }
      return this.selfService.getByIdOrIdentifier(identifier, {
        is_private: this.is_private,
      });
    }
  }
  return BaseReadByIdentifierController;
}
 
/**
 * A mixin factory for controllers to extend RUD by Identifier
 * @param superClass - Base class
 * @param options - Options for the controller
 * @typeParam M - Model class
 * @typeParam T - Base class
 */
function updateByIdentifierCtlMixin<M extends BaseEntity, T extends MixinTarget<BaseController>>(superClass: T, options: Options) {
  options = merge(cloneDeep(DEFAULT_ACL), options);
 
  class BaseUpdateByIdentifierController extends superClass implements IUpdateByIdentifier<M> {
    // Value will be provided by the subclassed controller class
    selfService: BaseService<M>;
 
    @service()
    public log_service: AuditLogService;
 
    /**
     * Update model by identifier.
     * @param identifier The identifier of model
     * @param model The new information
     * @returns Promise<void>
     */
    @patch(`/${options.basePath}/{identifier}`, {
      responses: {
        '204': {
          description: `${options.modelClass.modelName} PATCH success`,
        },
      },
    })
    @intercept(EnsureProvideDataInterceptor.BINDING_KEY)
    async updateByIdentifier(
      @param.path.string('identifier') identifier: string,
      @requestBody({
        content: {
          [CONTENT_TYPE.JSON]: {
            schema: getModelSchemaRefWithoutAutoPopulate(options.modelClass, {
              partial: true,
              exclude: options.schemaOptions['updateByIdentifier'].exclude,
            }),
          },
        },
      })
      model: M,
    ): Promise<void> {
      if (!this.is_private) {
        this.selfService.ensureRightAccessRecord();
      }
      const updated_inst = await this.selfService.updateByIdOrIdentifier(
        identifier,
        model,
        { is_private: this.is_private },
      );
      this.writeLog(
        options.modelClass,
        updated_inst?.id,
        updated_inst,
        updated_inst?.activity,
        updated_inst?.activity ? updated_inst.activity.args[0] as string : undefined,
      );
    }
  }
  return BaseUpdateByIdentifierController;
}
 
/**
 * A mixin factory for controllers to extend RUD by Identifier
 * @param superClass - Base class
 * @param options - Options for the controller
 * @typeParam M - Model class
 * @typeParam T - Base class
 */
function deleteByIdentifierCtlMixin<M extends BaseEntity, T extends MixinTarget<BaseController>>(superClass: T, options: Options) {
  options = merge(cloneDeep(DEFAULT_ACL), options);
 
  class BaseDeleteByIdentifierController extends superClass implements IDeleteByIdentifier {
    // Value will be provided by the subclassed controller class
    selfService: BaseService<M>;
 
    @service()
    public log_service: AuditLogService;
 
    /**
     * Delete model instance by identifier
     * @param identifier The identifier of model
     * @returns Promise<void>
     */
    @del(`/${options.basePath}/{identifier}`, {
      responses: {
        '204': {
          description: `${options.modelClass.modelName} DELETE success`,
        },
      },
    })
    async deleteByIdentifier(
      @param.path.string('identifier') identifier: string,
    ): Promise<void> {
      if (!this.is_private) {
        this.selfService.ensureRightAccessRecord();
      }
      const deleted_inst = await this.selfService.deleteByIdOrIdentifier(
        identifier,
        { is_private: this.is_private },
      );
 
      this.writeLog(
        options.modelClass,
        deleted_inst.id,
        deleted_inst,
        deleted_inst?.activity,
        deleted_inst?.activity ? deleted_inst.activity.args[0] as string : undefined,
      );
    }
  }
  return BaseDeleteByIdentifierController;
}
 
export function createBaseControllerFactory<M extends BaseEntity, T extends MixinTarget<BaseController>>(superClass: T, options: Options, extendOptions: ExtendOptions) {
  let finalClass = superClass;
  // Refactor to reduce cognitive complexity
  const extendFunctions: any = {
    isExtendCreate: createCtlMixin,
    isExtendRead: readCtlMixin,
    isExtendReadById: readByIdCtlMixin,
    isExtendUpdateById: updateByIdCtlMixin,
    isExtendDeleteById: deleteByIdCtlMixin,
    isExtendReadByIdentifier: readByIdentifierCtlMixin,
    isExtendUpdateByIdentifier: updateByIdentifierCtlMixin,
    isExtendDeleteByIdentifier: deleteByIdentifierCtlMixin,
  };
  for (const [key, value] of Object.entries(extendOptions)) {
    Eif (value) {
      finalClass = (extendFunctions[key] as (superClass: T, options: Options) => T)(finalClass, options);
    }
  }
 
  return finalClass;
}