All files / lib/lambda/middleware fetchChangelog.ts

100% Statements 12/12
85.71% Branches 6/7
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 50 51 52 53 54 55 56 57                12x                   12x 7x   7x   7x   7x 6x   6x 6x 1x                 6x   5x                              
import { Request } from "@middy/core";
import { getPackageChangelog } from "libs/api/package";
import { changelog } from "shared-types/opensearch";
 
import { getPackageFromRequest, storePackageInRequest } from "./utils";
 
export type FetchChangelogOptions = { setToContext?: boolean };
 
const defaults: FetchChangelogOptions = {
  setToContext: false,
};
 
/**
 * Fetches the changelog of the package, if there is any, and adds it 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 changelog before the handler runs
 */
export const fetchChangelog = (opts: FetchChangelogOptions = {}) => {
  const options = { ...defaults, ...opts };
 
  return {
    before: async (request: Request) => {
      const packageResult = await getPackageFromRequest(request);
 
      if (packageResult?._id) {
        const filter = [];
        // @ts-ignore legacy field
        const { legacySubmissionTimestamp } = packageResult._source;
        if (legacySubmissionTimestamp !== null && legacySubmissionTimestamp !== undefined) {
          filter.push({
            range: {
              timestamp: {
                gte: new Date(legacySubmissionTimestamp).getTime(),
              },
            },
          });
        }
 
        const changelog = await getPackageChangelog(packageResult._id, filter);
 
        storePackageInRequest(
          {
            ...packageResult,
            _source: {
              ...packageResult._source,
              changelog: changelog.hits.hits as changelog.ItemResult[],
            },
          },
          request,
          options.setToContext,
        );
      }
    },
  };
};