All files / src/interceptors ensure-provide-data.interceptor.ts

35.29% Statements 6/17
0% Branches 0/8
0% Functions 0/4
31.25% Lines 5/16

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                                                                                          
import {
  bind,
  Interceptor,
  InvocationContext,
  InvocationResult,
  Provider,
  ValueOrPromise,
} from '@loopback/core';
import {HttpErrors} from '@loopback/rest';
import {isEmpty, omit} from 'lodash';
 
/**
 * This class will be bound to the application as an `Interceptor` during
 * `boot`
 */
@bind({tags: {key: EnsureProvideDataInterceptor.BINDING_KEY}})
export class EnsureProvideDataInterceptor implements Provider<Interceptor> {
  static readonly BINDING_KEY = `interceptors.${EnsureProvideDataInterceptor.name}`;
  private readonly _updateMethodName = new Set<string>(['update', 'upsert']);
 
  /*
  constructor() {}
  */
 
  /**
   * This method is used by LoopBack context to produce an interceptor function
   * for the binding.
   *
   * @returns An interceptor function
   */
  value() {
    return this.intercept.bind(this);
  }
 
  /**
   * The logic to intercept an invocation
   * @param invocationCtx - Invocation context
   * @param next - A function to invoke next interceptor or the target method
   */
  async intercept(
    invocationCtx: InvocationContext,
    next: () => ValueOrPromise<InvocationResult>,
  ) {
    if (this._updateMethodName.has(invocationCtx.methodName)) {
      const data = this._getData(invocationCtx.args);
      if (isEmpty(data) || isEmpty(omit(data, 'id'))) {
        throw new HttpErrors.UnprocessableEntity('Missing data to update');
      }
    }
    // Add pre-invocation logic here
    const result = await next();
    // Add post-invocation logic here
    return result;
  }
 
  private _getData(args: any[]) {
    if (typeof args[0] === 'object') {
      return args[0];
    }
    return args[1];
  }
}