Skip to content

Instantly share code, notes, and snippets.

@singledigit
Created October 15, 2019 19:51
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save singledigit/facb18581d50852827000896d67b5e72 to your computer and use it in GitHub Desktop.
Lambda API Gateway Response Handler
const isLocal = process.env.AWS_SAM_LOCAL;
const handlerModel = (body, headers, code) => {
let response = {
'statusCode': code,
'body': JSON.stringify(body)
}
if(headers.length > 0) {
response.headers = response.headers || {};
headers.map(header => {
key = Object.keys(header)[0];
response.headers[key] = header[key];
})
}
if (isLocal) {
response.headers = response.headers || {};
response.headers['Access-Control-Allow-Origin'] = "*"
}
return new Promise((res, rej) => {
if(code === 500) rej(response)
else res(response);
})
}
exports.success = (body, headers = []) => {
return handlerModel(body, headers, 200)
}
exports.fail = (body, headers = [], code = 500) => {
return handlerModel(body, headers, code)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment