在定义我的 aws lambda 时,我通常使用新的 async/await 模式:
exports.handler = async (event) => {
// do stuff...
}
您通常不需要context,除非您想使用有关您的 lambda 的一些与 aws 相关的信息。
我有一个在代码库中被大量重复使用的辅助函数
function proxyResponse(inBody, inStatusCode = null, headers = {}, event = null) {
if (!isApiGateway(event)) {
if (inBody instanceof Error) {
throw inBody;
}
return inBody;
}
let statusCode = inStatusCode;
let body;
if (inBody instanceof Error) {
statusCode = statusCode || INTERNAL_SERVER_ERROR;
body = JSON.stringify({
message: inBody.message,
code: statusCode,
});
} else if (inBody instanceof Object) {
body = JSON.stringify(inBody);
} else {
body = inBody;
}
const [origin] = event ? caseHandler(event.headers, 'origin') : [];
return {
statusCode: statusCode || 200,
body,
headers: Object.assign({
'Access-Control-Allow-Headers': 'Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token,x-api-key,Authorization',
'Access-Control-Allow-Origin': origin,
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Methods': 'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT',
}, headers),
};
}
还有一个:
function caseHandler(mixedCaseObject, inputKey) {
if (!mixedCaseObject || !inputKey) {
return [];
}
return Object.keys(mixedCaseObject)
.filter((key => key.toLowerCase() === inputKey.toLowerCase()))
.map(key => mixedCaseObject[key]);
}
还有这个:
function isApiGateway(event) {
return (!!event.httpMethod && !!event.headers && !!event.requestContext);
}
所以每当我想返回一些东西时,我都会在 lambda 内部使用这个辅助函数:
module.exports.handler = async (event) => {
try{
// do stuff...
return proxyResponse(YOUR_CUSTOM_BODY_OBJECT, Api.HTTP.OK, {}, event);
} catch(error) {
return proxyResponse(error, Api.HTTP.INTERNAL_SERVER_ERROR, {}, event);
}
}