Created
February 26, 2018 22:21
-
-
Save tsdorsey/b94813a3c97e4c5decb296b6e2dbbe97 to your computer and use it in GitHub Desktop.
Revisions
-
tsdorsey created this gist
Feb 26, 2018 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,66 @@ export function buildResponse(statusCode, body, cors = true) { const result = { statusCode: statusCode || HTTP_STATUS.OK, }; if (cors) { result['headers'] = { 'Access-Control-Allow-Origin': '*', Accept: 'application/json', }; } if (body) { result.body = JSON.stringify(body); result.headers['Content-Type'] = 'application/json'; } return result; } export function httpRouter(handlerMap) { const notFound = async function(event, context, callback) { callback(undefined, buildResponse(404)); }; return async function(event, context, callback) { debug('httpRouter handle event:', readable(event)); const handler = get(handlerMap, event.httpMethod, notFound); if (handler === notFound) { debug( `Failed to find handler for event: ${readable( event, )}\nAnd context: ${readable(context)}`, ); } return handler(event, context, callback); }; } export function groupedEventHandler(handlers) { return async function(event, context, callback) { const errors = []; for (let handlerName of Object.keys(handlers)) { debug(`START EVENT HANDLER: ${handlerName}`); const handler = handlers[handlerName]; try { await handler(event, context); } catch (err) { debug(`ERROR IN EVENT HANDLER: ${handlerName}`); debug(err); debug(err.stack); errors.push(err); } debug(` END EVENT HANDLER: ${handlerName}`); } if (errors.length > 0) { callback(errors); } callback(); }; }