All files / lib/lambda/middleware fetchChangelog.ts

86.66% Statements 13/15
71.42% Branches 5/7
100% Functions 2/2
86.66% Lines 13/15

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 58 59 60 61 62 63 64 65 66                  3x                   3x 5x   5x   5x   5x 5x   5x 5x 1x                   5x 5x               5x                              
import { Request } from "@middy/core";
import { createError } from "@middy/util";
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);
 
      Eif (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(),
              },
            },
          });
        }
 
        let changelog;
        try {
          changelog = await getPackageChangelog(packageResult._id, filter);
        } catch (err) {
          console.error(err);
          throw createError(500, JSON.stringify({ message: "Internal server error" }), {
            expose: true,
          });
        }
 
        storePackageInRequest(
          {
            ...packageResult,
            _source: {
              ...packageResult._source,
              changelog: changelog.hits.hits as changelog.ItemResult[],
            },
          },
          request,
          options.setToContext,
        );
      }
    },
  };
};