2.1.2 • Published 3 years ago

io-ts-serverless-handler v2.1.2

Weekly downloads
2
License
Apache-2.0
Repository
github
Last release
3 years ago

io-ts-serverless-handler

Commitizen friendly

A simple wrapper for Serverless Framework HTTP handlers to remove the boilerplate of using io-ts codecs to validate and extract request parameters.

Usage

Install with npm/yarn:

$ yarn add io-ts-serverless-handler
# or npm i --save io-ts-serverless-handler

Create a file where you configure the wrapper function and export it:

// codec-handler.ts

import { configureWrapper } from "io-ts-serverless-handler";

export const codecHandler = configureWrapper({
  // Add optional config here
});

Wrap your handler functions with the wrapper function:

import { codecHandler } from "./codec-handler.ts";
import { NumberFromString } from "io-ts-types/lib/NumberFromString";

export const getUsers = codecHandler(
  {
    queryParameters: t.partial({
      pageSize: NumberFromString,
      pageNumber: NumberFromString
    }),
    pathParameters: t.type({
      userId: NumberFromString
    })
  },
  async ({
    queryParameters: { pageSize, pageNumber },
    pathParameters: { userId }
  }) => {
    // At this point, all the parameters have been validated by io-ts
    // If a validation error occurred, a 400 would have been returned before this point
    return userService.getUser(userId, pageNumber, pageSize);
  }
);

The request body will parsed as JSON and then passed to your codec.

All the other parameters from API Gateway will come through as strings so if you want to decode a non-string type you will have to use a codec that accepts a string, converts it to the type you want and than validates that.

There are a lot of types in the io-ts-types library that can do this for you such as NumberFromString or BooleanFromString.

Roadmap

  1. Better documentation
  2. CI/CD
  3. Support for serverless handlers for providers other than AWS
2.1.2

3 years ago

2.1.1

4 years ago

2.1.0

4 years ago

2.0.1

4 years ago

2.0.0

4 years ago

1.0.4

4 years ago

1.0.3

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago