@lambda-middleware/json-deserializer
A middleware for AWS http lambda functions to deserialize incoming requests containing a json body.
Depending on the request payload and header the following can happen:
- The event has a valid json content-type header (eg.
application/json
), and:- The body contains a valid JSON payload -
body
is deserialized and added back to the event object asbodyObject
with a type ofRecord<string, unknown>
. - The body has invalid JSON payload - the middleware throws a
RequestBodyNotJsonError
.
- The body contains a valid JSON payload -
- The event has a non json content-type header - the middleware will add a
bodyObject
property withnull
. - The event has no body set - the middleware will add a
bodyObject
property withnull
.
Please note that this middleware just provides a basic object to the handler without typing for the properties, you will need to handle validation of the request body object separately.
Lambda middleware
This middleware is part of the lambda middleware series. It can be used independently.
Usage
import { jsonDeserializer } from "@lambda-middleware/json-deserializer";
import { APIGatewayProxyEvent, APIGatewayProxyResult } from "aws-lambda";
import { APIGatewayProxyObjectEvent } from "../lib/types/APIGatewayProxyObjectEvent";
// This is your AWS handler
async function helloWorld(
request: APIGatewayProxyObjectEvent<APIGatewayProxyEvent>
): Promise<APIGatewayProxyResult> {
// We can simply pick out the body object from the request and use it
const { bodyObject } = request ?? {};
// Do something with the object and return it
return {
statusCode: 200,
body: JSON.stringify({
...bodyObject,
additionalThing: "addedInHandler",
}),
};
}
// Wrap the handler with the middleware
export const handler = jsonDeserializer()(helloWorld);