import * as parser from "body-parser" ; import { Router } from "express" ; import * as glob from "glob" ; import * as normalize from "header-case-normalizer" ; import * as path from "path" ; import { mockAPIGatewayProxyEvent } from "_/mocks/vendor/aws-lambda" ; return export async function middleware ( ) { const router = Router ( ) ; router . use ( parser . json ( ) ) ; const base = path . resolve ( __dirname , "../../../src/handlers" ) ; await Promise . all ( glob . sync ( path . resolve ( base , "!(_)/**/*.ts" ) ) . map ( async ( file ) => { const handlers = await import ( file ) ; const name = path . dirname ( path . relative ( base , file ) ) . replace ( "verify" , ":code" ) ; Object . keys ( handlers ) . forEach ( method => { const handler = handlers [ method ] ; router [ method as "get" | "post" ] ( `/${ name }` , async ( req , res ) => { const normalizedHeaders = Object . keys ( req . headers ) . reduce < { [ name ] : string ; } > ( ( result , header ) => { result [ normalize ( header ) ] = req . headers [ header ] as string ; return result ; } , { } ) ; const event = mockAPIGatewayProxyEvent ( { path : req . url , pathParameters : req . params , headers : normalizedHeaders , method : req . method as "GET" | "POST" , body : JSON . stringify ( req . body ) } ) ; await new Promise ( resolve => setTimeout ( resolve , 100 ) ) ; try { const { statusCode , headers , body } = await handler ( event ) ; res . statusCode = statusCode ; res . set ( headers || { } ) ; res . end ( body ) ; } catch ( err ) { res . statusCode = 500 ; res . end ( ) ; } } ) ; } ) ; } ) ) ; return router ; }