问题
I am trying to properly setup Body Mapping and Header Mapping in the Integration Response for an API Gateway endpoint.
In our Lambda we have
if (response.statusCode == 200) {
context.succeed(output);
} else if (response.statusCode == 206) {
var paginationObject = {
errorType : "PartialContent",
errorCode : 206,
detailedMessage : "PartialContent Returned",
stackTrace : [],
data : {
output
}
};
context.fail(JSON.stringify(paginationObject));
}
I then handle fetching this in the Integration Response using a Lambda Error Regex of .*PartialContent.* and have my Body Mapping Template as
#set($allParams = $input.params())
#set($body = $util.parseJson($input.json('$.errorMessage')))
$body
This gives me the correct HTTP status code and JSON output, but it has too much data in the body. The response looks like:
{
"errorType":"PartialContent",
"errorCode":206,
"detailedMessage":"PartialContent Returned",
"stackTrace":[],
"data":{
"output":{
"status":206,
"bodyJson":[{"call_date":"2017-08-19 18:17:21"}],
"headers":{"date":"Thu, 02 Nov 2017 18:36:52 GMT",
"server":"Apache",
"x-pagination-page-size":10}
}
}
}
I want the headers to actually appear as headers in the response, and I want the body to just be the content inside of bodyJson
I've tried to change the body mapping template to use $body.data.output.bodyJson, but when I do that the body is completely empty. I've also got the headers set in the Header Mappers, trying both integration.response.body.headers.x-pagination-page-size and integration.response.header.x-pagination-page-size but both times the header is blank, even though I can see the proper values in the JSON output.
How do I get just the bodyJson element to be output as the body of the response? And how do I properly get the headers mapped?
回答1:
Did you try to use Lambda Error Regex in Integration Response? For example:
.*"status":400.*
body mapping templetes:
#set ($errorMessageObj = $util.parseJson($input.path('$.errorMessage')))
{
"status" : "$errorMessageObj.status",
"errorType" : "$errorMessageObj.errorType",
"message" : "$errorMessageObj.errorMessage"
}
I created an error function in my Lamda:
function error(status, errorType, errorMessage, callback){
callback(JSON.stringify({
status: status,
errorType: errorType,
errorMessage: errorMessage
}));
}
usage:
error(404, "Not Found", "Resource is not found", callback);
来源:https://stackoverflow.com/questions/47082614/aws-api-gateway-header-and-body-mappings-in-integration-response