1- export default ( name : string ) : string => `Hello ${ name } !`
1+ import { NestApplicationOptions , INestApplication } from '@nestjs/common'
2+ import { NestFactory } from '@nestjs/core'
3+ import { Server } from 'http'
4+ import { ExpressAdapter } from '@nestjs/platform-express'
5+ import * as serverless from 'aws-serverless-express'
6+ import express from 'express'
7+ import { APIGatewayProxyEvent , Context , APIGatewayEvent } from 'aws-lambda'
8+
9+ let cachedServer : Server
10+
11+ export type NestAplicationCallback = (
12+ app : INestApplication ,
13+ ) => INestApplication | Promise < INestApplication > ;
14+ const defaultCallback : NestAplicationCallback = app => app
15+
16+ export class ServerlessNestjsApplicationFactory < T = any > {
17+ private readonly AppModule : T ;
18+ private options : NestApplicationOptions ;
19+ private callback : NestAplicationCallback ;
20+ constructor (
21+ AppModule : T ,
22+ options : NestApplicationOptions = { } ,
23+ callback : NestAplicationCallback = defaultCallback
24+ ) {
25+ this . AppModule = AppModule
26+ this . options = options
27+ this . callback = callback
28+ }
29+
30+ public updateOptions ( options : NestApplicationOptions ) {
31+ this . options = options
32+ return this
33+ }
34+
35+ public updateCallback ( callback : NestAplicationCallback ) {
36+ this . callback = callback
37+ return this
38+ }
39+
40+ public async createApplication ( ) {
41+ const expressApp = express ( )
42+ const adapter = new ExpressAdapter ( expressApp )
43+ const application = await NestFactory . create (
44+ this . AppModule ,
45+ adapter ,
46+ this . options
47+ )
48+ const app = await this . callback ( application )
49+ app . init ( )
50+ return serverless . createServer ( expressApp )
51+ }
52+
53+ public async create (
54+ event : APIGatewayProxyEvent | APIGatewayEvent ,
55+ context : Context
56+ ) {
57+ if ( ! cachedServer ) {
58+ cachedServer = await this . createApplication ( )
59+ }
60+ const result = await serverless . proxy (
61+ cachedServer ,
62+ event ,
63+ context ,
64+ 'PROMISE'
65+ ) . promise
66+ return result
67+ }
68+ }
0 commit comments