aws-lambda-router
aws-lambda-router copied to clipboard
Doesn't work with raw text bodies
I setup a POST route with a handler and the handler never got invoked despite debug mode logging that it found a matching route. The logs just end there.
I was able to eventually reproduce the issue and the response was Unexpected 'b'
.
I'm working on a PR to handle text types and add debug logging when the mime type isn't valid but I wanted to bring this up. I got around it by handing that specific route prior to calling the route handler like so:
module.exports.handler = async (event, context, callback) => {
if (event.path === "/myPath" && event.httpMethod === "POST") {
return controller.myPath(event, context, callback);
} else {
return router.handler(routeConfig)(event, context, callback);
}
};
Hi @beardyman, which version do you use? Maybe the PR #13 solves your problem. But this is not released yet.
Further more there is another PR #15 in the pipeline which handles error pathes better.
I'm using the latest version in npm(0.4.0). At first glance #13 looks like it would probably solve my issue of troubleshooting however it wouldn't handle the actual request. For non-JSON bodies it would have to either inspect the content type or try to parse as JSON and then fall back to plain text.
What I'm suggesting would basically be
if (event.body) {
try {
event.body = JSON.parse(event.body);
} catch () { /* swallow any parse errors and carry on as plain text */ }
}
rather than:
if (event.body) {
try {
event.body = JSON.parse(event.body);
} catch (parseError) {
return Promise.resolve({
statusCode: 400,
headers: headers,
body: JSON.stringify('body is not a valid JSON')
});
}
}
In my fork I solved this by creating a new property called "parsedBody". That way we don't break the AWS APIGatewayProxyEvent defined body type which is a string or null.
Also checking content-type header, if JSON I will add the result to the parsedBody body. This would allow for more parsers such as XML.
Would be happy to submit a PR to this library but it is a breaking change. Full code at: https://github.com/capcito/aws-lambda-router/blob/develop/lib/proxyIntegration.js#L100
const isJson = event.headers['Content-Type'] && event.headers['Content-Type'].toUpperCase() === 'APPLICATION/JSON';
if (event.body && isJson) {
try {
event.parsedBody = JSON.parse(event.body);
} catch (parseError) {
console.log(`Could not parse body as json: ${event.body}`, parseError);
return Promise.resolve({
statusCode: 400,
headers: headers,
body: JSON.stringify( { message: "body is not a valid JSON", error: "ParseError" })
});
}
}