@resourcefulhumans/rheactor-aws-lambda
Version:
Core components for RESTful AWS lambda endpoints
71 lines (61 loc) • 3.01 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.handler = handler;
var _bluebird = require('bluebird');
var _bluebird2 = _interopRequireDefault(_bluebird);
var _api = require('./api');
var _rheactorModels = require('rheactor-models');
var _rheactorValueObjects = require('rheactor-value-objects');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @param {String} contentType
* @param {String} environment
* @param {String} tokenSecretOrPrivateKey
* @param {Array.<Function>} operations
* @param {{headers: object, path: string, httpMethod: string, body: string, queryStringParameters: object, requestContext: object}} event
* @param {object} context
* @param {function} callback
*/
function handler(contentType, environment, tokenSecretOrPrivateKey, operations, event, context, callback) {
var statusCode = 200;
var done = function done(err, res) {
/* istanbul ignore next */
if (err && environment !== 'testing') console.error(err);
if (err && !(err instanceof _rheactorModels.HttpProblem)) {
err = new _rheactorModels.HttpProblem(new _rheactorValueObjects.URIValue('https://github.com/ResourcefulHumans/rheactor-aws-lambda#' + err.constructor.name), err.message, 400);
}
return callback(null, {
statusCode: err ? err.status : res ? statusCode : 204,
body: JSON.stringify(err || res),
headers: {
'Content-Type': contentType,
'Access-Control-Allow-Origin': '*'
}
});
};
var allowedMethods = /^(GET|POST)$/;
_bluebird2.default.try(function () {
(0, _api.checkContentType)(event, contentType);
var parts = event.path.split('/');
parts.shift();
var operation = parts.shift();
if (!operation.length || !operations[operation]) throw new _rheactorModels.HttpProblem(new _rheactorValueObjects.URIValue('https://github.com/ResourcefulHumans/rheactor-aws-lambda#Error'), 'Unknown operation "' + event.path + '"', 404);
if (!allowedMethods.test(event.httpMethod)) {
throw new _rheactorModels.HttpProblem(new _rheactorValueObjects.URIValue('https://github.com/ResourcefulHumans/rheactor-aws-lambda#Error'), 'Method not allowed: "' + event.httpMethod + '"', 405);
}
var method = event.httpMethod.toLowerCase();
if (typeof operations[operation][method] === 'undefined') {
throw new _rheactorModels.HttpProblem(new _rheactorValueObjects.URIValue('https://github.com/ResourcefulHumans/rheactor-aws-lambda#Error'), 'Unsupported operation "' + event.httpMethod + ' ' + event.path + '"', 400);
}
var body = event.body ? JSON.parse(event.body) : {};
return (0, _api.getOptionalToken)(event, tokenSecretOrPrivateKey).then(function (token) {
return operations[operation][method](body, parts, token, event.queryStringParameters, event.requestContext);
});
}).then(function (res) {
return done(null, res);
}).catch(function (err) {
return done(err);
});
}