UNPKG

@mcma/aws-api-gateway

Version:

Node module with code for using AWS's API Gateway as an entry point to an MCMA API handler.

66 lines (65 loc) 2.54 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ApiGatewayApiController = void 0; const core_1 = require("@mcma/core"); const api_1 = require("@mcma/api"); function isAPIGatewayProxyEvent(x) { return !!x.httpMethod; } class ApiGatewayApiController { apiController; config; constructor(routesOrConfig, loggerProvider, configVariables) { if (routesOrConfig instanceof api_1.McmaApiRouteCollection) { this.config = { routes: routesOrConfig, loggerProvider: loggerProvider, configVariables: configVariables, }; } else { this.config = routesOrConfig; } if (!this.config.configVariables) { this.config.configVariables = core_1.ConfigVariables.getInstance(); } this.apiController = new api_1.McmaApiController(this.config.routes, this.config.middleware); } async handleRequest(event, context) { let httpMethod, path; if (isAPIGatewayProxyEvent(event)) { httpMethod = event.httpMethod; path = this.config.includeStageInPath ? event.requestContext.path : event.path; } else { httpMethod = event.requestContext.http.method; path = this.config.includeStageInPath || event.requestContext.stage === "$default" ? event.requestContext.http.path : event.requestContext.http.path.substring(event.requestContext.stage.length + 1); } const requestContext = new api_1.McmaApiRequestContext(new api_1.McmaApiRequest({ id: context.awsRequestId, path, httpMethod, headers: event.headers, pathVariables: {}, queryStringParameters: event.queryStringParameters, body: event.body }), this.config.loggerProvider, this.config.configVariables); await this.apiController.handleRequest(requestContext); let body = requestContext.response.body; let isBase64Encoded = false; if (Buffer.isBuffer(body)) { isBase64Encoded = true; body = body.toString("base64"); } else if (typeof body === "object") { body = JSON.stringify(body); } return { statusCode: requestContext.response.statusCode, headers: requestContext.response.headers, body, isBase64Encoded }; } } exports.ApiGatewayApiController = ApiGatewayApiController;