All files / lib/lambda/middleware fetchPackage.ts

100% Statements 12/12
87.5% Branches 7/8
100% Functions 2/2
100% Lines 12/12

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                      12x                       12x 8x   8x     14x     14x 14x   5x 3x       11x 2x     9x        
import { MiddlewareObj, Request } from "@middy/core";
import { createError } from "@middy/util";
import { getPackage } from "libs/api/package";
 
import { storePackageInRequest } from "./utils";
 
export type FetchPackageOptions = {
  allowNotFound?: boolean;
  setToContext?: boolean;
};
 
const defaults: FetchPackageOptions = {
  allowNotFound: false,
  setToContext: false,
};
 
/**
 * Fetches a package and adds it to internal storage.
 * @param {object} opts Options for running the middleware
 * @param {boolean} opts.allowNotFound [false] if true, do not error if the package is not found
 * @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 a package before the handler runs
 */
export const fetchPackage = (opts: FetchPackageOptions = {}): MiddlewareObj => {
  const options = { ...defaults, ...opts };
 
  return {
    before: async (request: Request) => {
      // the event body should already have been validated by `validator` before this handler runs
      const { id } = request.event.body as { id: string };
 
      let packageResult;
      try {
        packageResult = await getPackage(id);
      } catch (err) {
        if (!options.allowNotFound) {
          throw err;
        }
      }
 
      if (!options.allowNotFound && (packageResult === undefined || !packageResult.found)) {
        throw createError(404, JSON.stringify({ message: "No record found for the given id" }));
      }
 
      storePackageInRequest(packageResult, request, options.setToContext);
    },
  };
};