Skip to content

Latest commit

 

History

History

json-deserializer

@lambda-middleware/json-deserializer

npm version downloads open issues debug build status codecov dependency status devDependency status

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 as bodyObject with a type of Record<string, unknown>.
    • The body has invalid JSON payload - the middleware throws a RequestBodyNotJsonError.
  • The event has a non json content-type header - the middleware will add a bodyObject property with null.
  • The event has no body set - the middleware will add a bodyObject property with null.

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);