All files / lib/lambda/middleware fetchAppkChildren.ts

84.61% Statements 11/13
57.14% Branches 4/7
100% Functions 2/2
84.61% Lines 11/13

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                3x                   3x 4x   4x   4x   4x   4x   2x 2x               2x 2x                                  
import { MiddlewareObj, Request } from "@middy/core";
import { createError } from "@middy/util";
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);
 
      Eif (packageResult?._id) {
        // @ts-ignore appkParent is a legacy field
        if (packageResult?._source?.appkParent) {
          let children;
          try {
            children = await getAppkChildren(packageResult._id);
          } catch (err) {
            console.error(err);
            throw createError(500, JSON.stringify({ message: "Internal server error" }), {
              expose: true,
            });
          }
 
          Eif (children?.hits?.hits?.length > 0) {
            storePackageInRequest(
              {
                ...packageResult,
                _source: {
                  ...packageResult._source,
                  appkChildren: children.hits.hits,
                },
              },
              request,
              options.setToContext,
            );
          }
        }
      }
    },
  };
};