UNPKG

@enter-at/lambda-handlers

Version:

An opinionated Typescript package that facilitates specifying AWS Lambda handlers including input validation, error handling and response formatting.

78 lines (77 loc) 2.87 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.APIGatewayProxyHandler = void 0; const error_1 = require("../error"); const UnprocessableEntityError_1 = require("../error/UnprocessableEntityError"); const header_1 = require("../header"); const response_1 = require("../response"); const BaseHandler_1 = require("./BaseHandler"); class APIGatewayProxyHandler extends BaseHandler_1.BaseHandler { constructor(args) { var _a; super(args); this.corsHeader = (_a = args === null || args === void 0 ? void 0 : args.cors) !== null && _a !== void 0 ? _a : new header_1.CORSHeader("*", true); } static handleError(err) { if (err instanceof error_1.ForbiddenError) { return response_1.forbidden(err.details); } if (err instanceof error_1.UnauthorizedError) { return response_1.unauthorized(err.details); } if (err instanceof error_1.BadRequestError || err instanceof error_1.FormatError || err instanceof error_1.ValidationError) { return response_1.badRequest(err.details); } if (err instanceof error_1.RequestTimeoutError) { return response_1.requestTimeout(err.details); } if (err instanceof UnprocessableEntityError_1.UnprocessableEntityError) { return response_1.unprocessableEntity(err.details); } if (err instanceof error_1.NotFoundError) { return response_1.notFound(err.details); } return response_1.internalServerError(); } after(result) { result = result !== null && result !== void 0 ? result : response_1.noContent(); if (result.statusCode === undefined) { result = response_1.ok(result); } return this.createResponse(result); } onException(exception) { return this.createResponse(APIGatewayProxyHandler.handleError(exception)); } formatInput(event) { if (!event.body) { return event; } try { event.body = this.inputFormat.apply(event.body); return event; } catch (err) { throw err; } } formatOutput(result) { const { body, ...properties } = result; return { ...(body && { body: this.outputFormat.apply(body) }), ...properties, }; } createResponse(result) { result.headers = this.createHeaders(result.headers); return this.formatOutput(result); } createHeaders(headers) { return { ...headers, ...(this.corsHeader && this.corsHeader.create()), ...(this.outputFormat && new header_1.ContentTypeHeader(this.outputFormat.contentType).create()), }; } } exports.APIGatewayProxyHandler = APIGatewayProxyHandler;