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 | 3x 3x 7x 7x 13x 13x 13x 4x 4x 2x 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) {
console.error(err);
if (!options.allowNotFound) {
// if you don't use the expose option here, you won't be able to see the error message
throw createError(500, JSON.stringify({ message: "Internal server error" }), {
expose: true,
});
}
}
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);
},
};
};
|