UNPKG

@incdevco/framework

Version:
205 lines (112 loc) 3.69 kB
'use strict'; var Promise = require('bluebird'); var Request = require('./request'); var Response = require('./response'); class API { constructor(logger) { this.logger = logger || console; this.routes = {}; } afterEachRequest(request, response) { return true; } beforeEachRequest(request, response) { return true; } eventToRequest(event) { event.params = event.params || {}; var request = new Request({ body: event.body, cognito: event.cognito, headers: event.params.header, method: event.httpMethod || event.method, params: event.params.path || {}, path: event.originalPath || event.path, query: event.params.query || event.params.querystring || {}, querystring: event.params.querystring }); return request; } eventToResponse(event) { var response = new Response({}); return response; } error() { return this.logger.error.apply(this.logger, arguments); } handleException(exception, request, response) { var throwOriginal = false; this.error(exception); if (exception.message.indexOf('Not Allowed') >= 0 || exception.message.indexOf('Not Found') >= 0 || exception.message.indexOf('Not Valid') >= 0 || exception.message.indexOf('conditional request failed') >= 0) { throwOriginal = true; } if (throwOriginal) { throw exception; } else { var newException = new Error('An Error Occurred'); throw newException; } } handleRequest(event) { var request, response; var self = this; return Promise.try(function () { request = self.eventToRequest(event); response = self.eventToResponse(event); return self.beforeEachRequest(request, response); }) .then(function () { return self.routeRequest(request); }) .then(function (handler) { return handler(request, response); }) .then(function () { return self.afterEachRequest(request, response); }) .then(function (result) { return self.handleSuccess(result, request, response); }) .catch(function (exception) { return self.handleException(exception, request, response); }); } handleSuccess(result, request, response) { return Promise.try(function () { return response; }); } log() { return this.logger.log.apply(this.logger, arguments); } register(path, method, handler) { this.routes[path] = this.routes[path] || {}; this.routes[path][method] = handler; return this; } routeRequest(request) { var method = request.method; var path = request.path; var routes = this.routes; return Promise.try(function () { var handler, type; if (!routes[path]) { console.log('routes', path, routes); throw new Error('Resource Not Found: ' + path); } if (!routes[path][method]) { throw new Error('Method Not Found'); } handler = routes[path][method]; type = typeof handler; if (type === 'function') { return handler; } throw new Error('Handler is not function: ' + type); }); } } module.exports = API;