0.0.1 • Published 3 years ago

@lapc/aws-function-utils v0.0.1

Weekly downloads
2
License
MIT
Repository
-
Last release
3 years ago

@lapc/aws-function-utils

Utilities for working with AWS Functions (i.e. with Netlify, etc.).

General notes

AWS functions (aka Handlers) look like: (Event, Context) => Promise<Response>

  • The Event object contains meta data about the incoming request (POST body, query string, etc.)
  • The Context object contains additional contextual data. Higher order functions (see below) decorate this object with additional values.
  • The Response object contains what to return to the client.

Most functions in this library are implemented as higher order functions, that take a Handler, and return a new Handler that receives additional fields in its context, is wrapped in a response decorator, or is otherwise given additional, generic abilities.

Higher order functions

hofs/withConfigFactory

Attaches a config object to handler context. A convenience wrapper around hofs/withContextDecoratorFactory.

type Config = {
   helloMessage: string;
};

const decoratedHandler: ALBHandler<WithConfig<Config>> = async (event, context) => {
    const { config } = context;
    return success({
        message: `Hello message was ${config.helloMessage}`,
    });
};

// Creates a handler which automatically receives the config object in its context
export const handler = withConfig<Config>({
    helloMessage: "Hello, world!",
})(decoratedHandler);

hofs/withContextDecoratorFactory

Attaches an arbitrary decoration, generated asynchronously, to the context.

type Decoration = {
    decoratedValue: number;
}

// A handler that receives decorated context
const decoratedHandler: ALBHandler<ALBContext & Decoration> = async (event, context) => {
    const { decoratedValue } = context;
    return success({
        decoratedValue,
    });
};

// A function that takes an undecorated context and returns asynchronously a decorated one
const decorator = async (undecoratedContext: ALBContext): Promise<ALBContext & Decoration> => {
    return {
        ...undecoratedContext,
        decoratedValue: Math.random(),
    };
};

// Creates a handler which resolves the decorator function and passes the decorated context into the original handler
export const handler = withContextDecoratorFactory(decorator)(decoratedHandler);

Todo

  • More details in readme
  • More tests