All files / lib/lambda/middleware fetchAppkChildren.ts

100% Statements 10/10
71.42% Branches 5/7
100% Functions 2/2
100% Lines 10/10

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              12x                   12x 6x   6x   6x   6x   5x 3x   2x 2x                                  
import { MiddlewareObj, Request } from "@middy/core";
import { getAppkChildren } from "libs/api/package";
 
import { getPackageFromRequest, storePackageInRequest } from "./utils";
 
export type FetchAppkChildrenOptions = { setToContext?: boolean };
 
const defaults: FetchAppkChildrenOptions = {
  setToContext: false,
};
 
/**
 * Fetches any Appk children of the package and adds them to the package in internal storage.
 * @param {object} opts Options for running the middleware
 * @param {boolean} opts.setToContext [false] if true, also stores the package in context, so it can be accessed in the handler
 * @returns {MiddlewareObj} middleware to fetch the Appk children before the handler runs
 */
export const fetchAppkChildren = (opts: FetchAppkChildrenOptions = {}): MiddlewareObj => {
  const options = { ...defaults, ...opts };
 
  return {
    before: async (request: Request) => {
      const packageResult = await getPackageFromRequest(request);
 
      if (packageResult?._id) {
        // @ts-ignore appkParent is a legacy field
        if (packageResult?._source?.appkParent) {
          const children = await getAppkChildren(packageResult._id);
 
          Eif (children?.hits?.hits?.length > 0) {
            storePackageInRequest(
              {
                ...packageResult,
                _source: {
                  ...packageResult._source,
                  appkChildren: children.hits.hits,
                },
              },
              request,
              options.setToContext,
            );
          }
        }
      }
    },
  };
};