import flatten from '@tinkoff/utils/array/flatten' ; import isFunction from '@tinkoff/utils/is/function' ; import type { RequestHandler } from 'express' ; import { Router } from 'express' ; import type { Chain , Papi } from './types' ; import { getPapiParameters } from './createPapiMethod' ; function convert ( papis ) { const paths = new Set ( ) ; const result = [ ] ; for ( const papi of papis ) { const papiParams = getPapiParameters ( papi ) ; if ( ! papiParams ) { throw new Error ( `papi should be created using createPapiMethod from @tramvai/papi,
      got: ${ JSON . stringify ( papi ) }` ) ; } const key = `${ papiParams . method } ${ papiParams . path }` ; if ( paths . has ( key ) ) { throw new Error ( `papi: route '${ key }' already registered` ) ; } result . push ( papiParams ) ; paths . add ( key ) ; } return result ; } export function create ( papis , chain ) { const papiParams = convert ( papis ) ; const router = Router ( { strict : false , } ) ; router . use ( ( req , res , next ) => { res . setHeader ( 'cache-control' , 'no-cache,no-store,max-age=0,must-revalidate' ) ; next ( ) ; } ) ; for ( const papi of papiParams ) { const middlewaresMaybeArray = chain . map ( ( createMiddleware ) => createMiddleware ( papi ) ) ; const middlewares = flatten ( middlewaresMaybeArray ) . filter ( isFunction ) ; if ( papi . options . trimPapiUrl ) { const subRouter = Router ( { strict : false , } ) ; subRouter [ papi . method ] ( '*' , middlewares ) ; router . use ( papi . path , subRouter ) ; } else { router [ papi . method ] ( papi . path , middlewares ) ; } } router . use ( ( req , res ) => { if ( res . headersSent ) { return ; } res . status ( 404 ) ; res . json ( { resultCode : 'Not found' , payload : { } , } ) ; } ) ; return router ; }