@lamware/memoize
TypeScript icon, indicating that this package has built-in type declarations

3.0.1 • Public • Published
NPM Discord Apache-2.0

Lamware - Variable Memoize

This Lamware Middleware allows you to memoize variables and instances outside of the Lambda Handler with ease.

Why?

A lesser known feature of Lambda is that variables declared outside of the handler persist through the handler lifecycle. Since a Lambda instance, once cold-started, stays alive for 5-15 minutes (varies based on activity and the type of Lambda function), this provides a clear performance gain over having all logic instantiated inside the handler itself, since it'll only execute once (on the first request/invocation).

Currently, Lambda doesn't support top-level async/await, meaning set-up that involves non-synchronous operations isn't as simple as placing it outside the handler. By allowing you to supply a closure, and Lamware having support for asynchronous initialization, this middleware allows you to asynchronously memoize/load outside of the handler.

Installation

This package is available via NPM:

yarn add @lamware/memoize

# or

npm install @lamware/memoize

Usage

import type { APIGatewayProxyHandlerV2 } from 'aws-lambda';
import { memoize } from '@lamware/memoize';
import { lamware } from '@lamware/core';

interface MemoizePayload {
  count: number;
}

const { handler } = lamware<APIGatewayProxyHandlerV2<any>>()
  .use(memoize<MemoizePayload>(async () => {
    return { count: 1 };
  }, {
    // [optional] Whether to throw an `Error` if the memoize closure fails [default: true]
    throwOnError: false,
  }))
  .execute(async ({ state }) => {
    return {
      statusCode: 200,
      message: 'count should always be `1` since it is memoized!',
      count: state.count,
    };
  });

export { handler };

Package Sidebar

Install

npm i @lamware/memoize

Weekly Downloads

19

Version

3.0.1

License

GPL-3.0-only

Unpacked Size

39.7 kB

Total Files

7

Last publish

Collaborators

  • oyed