Skip to content

Instantly share code, notes, and snippets.

@tsdorsey
Created February 26, 2018 22:21
Show Gist options
  • Save tsdorsey/b94813a3c97e4c5decb296b6e2dbbe97 to your computer and use it in GitHub Desktop.
Save tsdorsey/b94813a3c97e4c5decb296b6e2dbbe97 to your computer and use it in GitHub Desktop.
Stopgap for the 200 resource limit in AWS by compressing the endpoint count
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();
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment