Skip to content

Instantly share code, notes, and snippets.

@tsdorsey
Created February 26, 2018 22:21
Show Gist options
  • Select an option

  • Save tsdorsey/b94813a3c97e4c5decb296b6e2dbbe97 to your computer and use it in GitHub Desktop.

Select an option

Save tsdorsey/b94813a3c97e4c5decb296b6e2dbbe97 to your computer and use it in GitHub Desktop.

Revisions

  1. tsdorsey created this gist Feb 26, 2018.
    66 changes: 66 additions & 0 deletions groupedHandler.js
    Original 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();
    };
    }