Serializer Middleware
Last updated:
Configuration
The middleware is configured by defining some serializers.
serializersMiddleware(
[
{
regex: /^application\/xml$/,
serializer: (data) => `<message>${data}</message>`,
},
{
regex: /^application\/json$/,
serializer: (data) => JSON.stringify(data)
},
{
regex: /^text\/plain$/,
serializer: (data) => data
}
],
'application/json'
)The defaultContentType (optional) option is used if the request and handler don't specify what type is wanted.
Serializer Functions
When a matching serializer is found, the Content-Type header is set and the serializer function is run.
The function is passed the entire data object, and should return a string.
If a string is returned, the body attribute of the response is updated.
If an object with a body attribute is returned, the entire response object is replaced. This is useful if you want to manipulate headers or add additional attributes in the Lambda response.
Content Type Negotiation
The header is not the only way the middleware decides which serializer to execute.
The content type is determined in the following order:
- The
Acceptheader via accept defaultContentTypemiddleware option
All options allow for multiple types to be specified in your order of preference, and the first matching serializer will be executed.