UNPKG

convert-lambda-to-express

Version:

Wrapper to run lambda on express. Works great for running lambdas as an express server during development but is production ready. Developed to work in conjunction with matthewkeil/full-stack-pattern cdk construct.

61 lines (60 loc) 2.38 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.wrapLambda = exports.getCredentials = void 0; const aws_sdk_1 = require("aws-sdk"); const Context_1 = require("./Context"); const Event_1 = require("./Event"); const convertResponse_1 = require("./convertResponse"); const runHandler_1 = require("./runHandler"); function getCredentials(filename, profile) { var _a, _b; if (filename) { const credentials = new aws_sdk_1.SharedIniFileCredentials({ filename, profile }); if (!!credentials.accessKeyId && !!credentials.secretAccessKey) { return credentials; } } if (((_a = process.env.AWS_ACCESS_KEY_ID) === null || _a === void 0 ? void 0 : _a.length) && ((_b = process.env.AWS_SECRET_ACCESS_KEY) === null || _b === void 0 ? void 0 : _b.length)) { return new aws_sdk_1.Credentials({ accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, sessionToken: process.env.AWS_SESSION_TOKEN }); } } exports.getCredentials = getCredentials; function wrapLambda(handler, options = {}) { var _a, _b; const logger = (_a = options.logger) !== null && _a !== void 0 ? _a : console; const credentials = getCredentials((_b = options.credentialsFilename) !== null && _b !== void 0 ? _b : '~/.aws/credentials', options.profile); return async (req, res, next) => { try { const startTime = Date.now(); const context = new Context_1.Context({ ...options, startTime, credentials }); const event = new Event_1.Event({ ...options, req, startTime, awsRequestId: context.awsRequestId, accountId: context._accountId }); const convertResponse = (0, convertResponse_1.convertResponseFactory)({ res, logger, options }); await (0, runHandler_1.runHandler)({ logger, handler, event, context, callback: convertResponse }); } catch (err) { // if server error building Event, Context or convertResponse return next(err); } }; } exports.wrapLambda = wrapLambda;