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(); }; }