npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

lambda-mdl

v1.2.7

Published

Type-safe middleware for AWS Lambda

Downloads

9

Readme

Type-safe middleware for AWS Lambda

Leveraging the power of Typescript to build middleware-like request handlers for lambda functions with type-based dependency checking.

TypeScript Test Coverage Status

Gif

An example

A service which parse request body as JSON, get a and b from it, check if both are valid numbers, then adds them and return result.

import { Err, MiddlewareCreator, Handler, JsonBodyService, ok, fail, creator, addService, jsonBodyService } from 'lambda-mdl';

type NumberService = { a: number; b: number };
type NumberErrNaN = Err<'NaA'>;
type NumberDependencies = JsonBodyService;

const numbers: MiddlewareCreator<{}, NumberService, NumberErrNaN, NumberDependencies> = () => {
  return async (request) => {
    const body = request.service.jsonBody;

    if (!(Number.isFinite(body.a) && Number.isFinite(body.b))) {
      return fail<NumberErrNaN>('NaA');
    }

    const service = body as NumberService;

    return addService(request, service);
  };
};

type Options = { acceptFloat: boolean };
type AdderService = { add: (a: number, b: number) => number };
type AdderErrNoFloats = Err<'Float'>;

const adder: MiddlewareCreator<Options, AdderService, AdderErrNoFloats> = (options, { throws }) => {
  return async (request) => {
    const service: AdderService = {
      add: (a: number, b: number) => {
        if (!options.acceptFloat && !(Number.isInteger(a) && Number.isInteger(b))) {
          throws<AdderErrNoFloats>('Float');
        }

        return a + b;
      },
    };

    return addService(request, service);
  };
};

const handler: Handler<AdderService & NumberService, number, never> = async ({
  service: { a, b, add },
}) => {
  return ok(add(a, b));
};

const lambda = creator(jsonBodyService).srv(numbers).srv(adder).ok(handler);

API

Defining services

Static service:

MiddlewareCreator

Type used for creating new services.

Params:

  • Options
  • Service
  • Errors
  • ServiceDeps
  • Event
import { Err, MiddlewareCreator, addService } from 'lambda-mdl';

type Options = { };
type Service = { add: (a: number, b: number) => number };
type Errors = never;

const service: MiddlewareCreator<Options, Service, Errors> = () => {
  return async (request) => {
    return addService(request, {
      add: (a: number, b: number) => {
        return a + b;
      },
    });
  };
};
Dynamic service:

Middleware

Used to define services dynamically based on provided options.

Params:

  • Service
  • Errors
  • ServiceDeps
  • Event
import { Middleware, ServiceContainer, Request, AwsEvent, empty, addService, creator } from 'lambda-mdl';

type Options = { test: number };
type Service<Opt> = Opt;
type Errors = never;

const service = <Opt extends Options>(
  options: Partial<Opt>
): Middleware<Opt, { data: Service<Opt> }, Errors> => {
  return async <Srv extends ServiceContainer>(request: Request<AwsEvent, Opt, Srv>) => {
    return addService(request, {
      data: { test: options.test } as Service<Opt>,
    });
  };
};

const res = creator(empty).opt({ test: 1 }).srv(service);

Initialization

creator

Starts the creation of the lambda chain.

Params:

  • creator: MiddlewareCreator
import { creator, empty } from 'lambda-mdl';

const res = creator(empty); // now you can use other methods, for example: .srv 

srv

Adds a new service.

Params:

  • creator: MiddlewareCreator
import { MiddlewareCreator, creator, empty, addService } from 'lambda-mdl';

const service: MiddlewareCreator<{}, {}, never> = () => {
  return async (request) => {
    return addService(request, {});
  }
};

const res = creator(empty).srv(service); 

opt

Set the options.

Params:

  • options

Handlers

ok

Adds a handler which will be run if all middleware creators executed successfully.

Params:

  • handler: Handler
import { ok, creator, empty } from 'lambda-mdl';

const res = creator(empty).ok(async () => {
  return ok('success'); // can be used in onOk
});

fail

Adds a handler which runs on middleware failure.

Params:

  • handler: HandlerError
import { ok, creator, empty } from 'lambda-mdl';

const res = creator(empty).fail(async () => {
  // this handler will not run because 
  // empty middleware won't fail
  
  return ok('success'); // can be used in onFail
});

fatal

Adds an unknown exception handler.

Params:

  • handler: HandlerException
import { ok, creator, empty } from 'lambda-mdl';

const res = creator(empty).fatal(async () => {
  // this handler will not run because 
  // empty middleware won't throw fatal errors
  
  return ok('success'); // can be used in onFatal
});

Transforms

onOk, onOkRes

Sets the result transformation of ok handler.

Params:

  • transform: Transform
import { ok, creator, empty } from 'lambda-mdl';

const res = creator(empty).ok(async () => {
  return ok('success');
}).onOk(async (result) => {
  return result; // result equals to 'success'
});

onFail, onFailRes

Sets the result transformation of fail handler.

Params:

  • transform: TransformError
import { ok, creator, empty } from 'lambda-mdl';

const res = creator(empty).fail(async () => {
  return ok('fail');
}).onFail(async (result) => {
  return result; // result equals to 'fail'
});

onFatal, onFatalRes

Sets the result transformation of fatal handler.

Params:

  • transform: TransformError
import { ok, creator, empty } from 'lambda-mdl';

const res = creator(empty).fatal(async () => {
  return ok('fatal');
}).onFatal(async (result) => {
  return result; // result equals to 'fatal'
});

on

Same as calling onOk, onFail and onFatal.

req

Returns AWS Lambda handler.


Packages

Packages allow grouping a service, and ok and fail handlers together.

import { Err, fail, ok } from 'lambda-res';
import { creator, empty, addService, ServiceOptions, Package } from 'lambda-mdl';

const pack: Package<
  ServiceOptions,
  { packageService: string },
  Err<'ServiceError'>,
  string,
  never,
  string
> = {
  srv: () => {
    return async (request) => {
      return addService(request, {
        packageService: 'service test',
      });
    };
  },
  ok: async () => {
    return ok(`ok`);
  },
  fail: async () => {
    return ok(`fail`);
  },
};

creator(empty)
  .pack(pack)
  .ok(async ({ service: { packageService } }) => {
    return ok(packageService);
  });