Created
October 15, 2019 19:51
-
-
Save singledigit/facb18581d50852827000896d67b5e72 to your computer and use it in GitHub Desktop.
Lambda API Gateway Response Handler
This file contains 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 characters
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