All files / src/interceptors ensure-id-valid.interceptor.ts

53.85% Statements 7/13
0% Branches 0/7
0% Functions 0/2
45.45% Lines 5/11

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 591x               1x         1x 1x           1x                                                                            
import {
  globalInterceptor,
  Interceptor,
  InvocationContext,
  InvocationResult,
  Provider,
  ValueOrPromise,
} from '@loopback/core';
import { HttpErrors } from '@loopback/rest';
 
/**
 * https://www.postgresql.org/docs/9.1/datatype-numeric.html
 */
export const MIN_ID_VALUE = 0;
export const MAX_ID_VALUE = 2147483647;
/**
 * This class will be bound to the application as an `Interceptor` during
 * `boot`
 */
@globalInterceptor('', { tags: { name: 'ensureIDValid' } })
export class EnsureIDValidInterceptor implements Provider<Interceptor> {
  /*
  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 (invocationCtx.methodName.startsWith('update')) {
      const id = invocationCtx.args[0];
      if (
        typeof id === 'number' &&
        (id < MIN_ID_VALUE || id > MAX_ID_VALUE)
      ) {
        throw new HttpErrors.BadRequest(`Invalid id ${id}`);
      }
    }
 
    // Add pre-invocation logic here
    return next();
  }
}