/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ import { Abstract, Type } from '@nestjs/common' import { Context, APIGatewayProxyHandler, SQSHandler } from 'aws-lambda' import { proxy, Response } from 'aws-serverless-express' import { get } from 'lodash' import { bootstrap, CORS, staticBootstrap } from './bootstrap' import { runNotificationHook } from './static.factory' export const runSQS = async (records: Array, name: string): Promise => { try { return await runNotificationHook(globalThis.cachedServer[name], records) } catch (error) { console.error(error) } } export const appFactory = ( app: any, staticController?: Type | Abstract | string | symbol, cors?: CORS, ): APIGatewayProxyHandler | SQSHandler => { const handler: APIGatewayProxyHandler | SQSHandler = async ( event: any, context: Context, ): Promise => { if (!get(globalThis, 'cachedServer')) globalThis.cachedServer = {} const isSQS = !!(event['Records'] && staticController) const name = app.prototype.constructor.name + (isSQS ? '.sqs' : '') if (!get(globalThis, `cachedServer.${name}`) || event.isOffline) globalThis.cachedServer[name] = await (isSQS ? staticBootstrap(app, staticController) : bootstrap(app, cors)) if (isSQS) return await runSQS(event['Records'], name) return proxy(globalThis.cachedServer[name], event, context, 'PROMISE').promise } return handler }