Skip to main content

Lazy

This framework is a helper framework that wraps another framework and receives a function to asynchronously initialize the application.

The constructor looks like:

lazy.framework.ts
constructor(
protected readonly framework: FrameworkContract<TApp>,
protected readonly factory: () => Promise<TApp>,
protected readonly logger: ILogger = createDefaultLogger(),
)

The first parameter is the instance of another framework, so if you want to use Express for example, you can just use like this:

import { ServerlessAdapter } from '@h4ad/serverless-adapter';
import { LazyFramework } from '@h4ad/serverless-adapter/frameworks/lazy';
import { ExpressFramework } from '@h4ad/serverless-adapter/frameworks/express';

const express = require('express');

async function bootstrap() {
const app = express();

// do the things asynchronously

return app;
}

const expressFramework = new ExpressFramework();
const framework = new LazyFramework(expressFramework, bootstrap);

export const handler = ServerlessAdapter.new(null)
.setFramework(framework)
// continue to set the other options here.
//.setHandler(new DefaultHandler())
//.setResolver(new PromiseResolver())
//.addAdapter(new AlbAdapter())
//.addAdapter(new SQSAdapter())
//.addAdapter(new SNSAdapter())
// after put all methods necessary, just call the build method.
.build();

Benefits

This is an optimized version that could save almost 1s (in my projects) because we initialize our app while the lambda warms up and before the lambda receives the first request.

tip

The solution above is inspired by top-level await, it is very much worth reading.

tip

Need to deal with CORS? See CorsFramework which helps you to add correct headers.