All files / api handleRouteLookup.ts

100% Statements 33/33
75% Branches 3/4
100% Functions 1/1
100% Lines 33/33

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 341x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
import Koa from 'koa';
 
import { errorResponse } from '@api/misc/httpResponse/errorResponse';
import { ModuleLookupType, koaRequestHandler } from '@api/types/handlerTypes';
import { ApiStatusErrorCode, IApiSegment, apiParams } from '@constants/api';
import { getLog } from '@services/internal/logService';
import { moduleLookup } from './module/moduleLookup';
import { IApiModule } from './types/baseModule';
 
export const handleRouteLookup =
  (props: {
    module?: ModuleLookupType;
    handlerFunc: (module: IApiModule<any, any, any>) => koaRequestHandler;
  }) =>
  async (ctx: Koa.DefaultContext, next: () => Promise<Koa.BaseResponse>) => {
    const segment = ctx.params[apiParams.general.segment];
    const innerModuleLookup = props.module ?? moduleLookup;
    const module = innerModuleLookup[segment as keyof IApiSegment];
    if (module == null) {
      const errMsg = `Correct route not found for ${segment}`;
      getLog().e(errMsg);
      await errorResponse({
        ctx,
        next,
        statusCode: ApiStatusErrorCode.segmentNotFound.code,
        message: errMsg,
      });
      return;
    }
 
    const handler = props.handlerFunc(module);
    await handler(ctx, next);
  };