UNPKG

express-lambda

Version:

Make AWS lambda behave like an express app

92 lines (83 loc) 3.1 kB
"use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var selectionPatterns = require("./selection_patterns"); var Response = function () { function Response(request, context) { _classCallCheck(this, Response); this.request = request; this.status("200"); this.data = null; this.context = context; } _createClass(Response, [{ key: "status", value: function status(statusCode) { this.statusCode = statusCode.toString(); return this; } }, { key: "location", value: function location(path) { this.data = path; return this; } }, { key: "send", value: function send() { if (arguments.length === 2) { this.status(arguments.length <= 0 ? undefined : arguments[0]); this.data = arguments.length <= 1 ? undefined : arguments[1]; } else { this.data = arguments.length <= 0 ? undefined : arguments[0]; } this.end(); } }, { key: "redirect", value: function redirect(code, location) { if (typeof code === "number" || typeof code === "string") { this.status(code); this.location(location); } else { this.status("302"); this.location(code); } this.end(); } }, { key: "end", value: function end() { var method = this.statusCode === "200" ? "succeed" : "fail"; var response; if (["201", "301", "302"].indexOf(this.statusCode) !== -1) { // hacky special handling for redirects so that we can reference the location as a header // for redirects the regex matches on presences of http(s) and various amounts of padding var padding = selectionPatterns.padding[this.statusCode]; response = padding + this.data; } else { response = ["STATUS" + this.statusCode, JSON.stringify(this.data)].join(selectionPatterns.responseDelimeter); } this.context[method](response); } }]); return Response; }(); module.exports = { makeRequest: function makeRequest(event, context) { var req = { query: event.query, params: event.params, body: event.body, context: event.context, method: event.method, get: function get(name) { return event.headers[name]; } }; return req; }, makeResponse: function makeResponse(event, context, req) { return new Response(req, context); } };