import { Binding , Component , ProviderMap , inject , CoreBindings , createBindingFromClass , } from '@loopback/core' ; import { ExpressRequestHandler , RestApplication } from '@loopback/rest' ; import { configure } from 'i18n' ; import { LocaleKey } from './enums' ; import { SFCoreBindings , OASBindings } from './keys' ; import { LoggerExtensionComponent } from './components' ; import { CoreConfig } from './types' ; import { Loopback4HelmetComponent } from 'loopback4-helmet' ; import { RateLimiterComponent } from 'loopback4-ratelimiter' ; import { OperationSpecEnhancer } from './enhancer/operation-spec-enhancer' ; import * as swstats from 'swagger-stats' ; export class CoreComponent implements Component { constructor ( @ inject ( CoreBindings . APPLICATION_INSTANCE ) private readonly application , @ inject ( SFCoreBindings . config , { optional : true } ) private readonly coreConfig , @ inject ( SFCoreBindings . EXPRESS_MIDDLEWARES , { optional : true } ) private readonly expressMiddlewares ) { const middlewares = [ ] ; if ( this . expressMiddlewares ) { middlewares . push ( ... this . expressMiddlewares ) ; } this . application . component ( LoggerExtensionComponent ) ; this . application . component ( Loopback4HelmetComponent ) ; this . application . component ( RateLimiterComponent ) ; if ( this . coreConfig ?. enableObf && this . coreConfig ?. openapiSpec ) { const swStatsMiddleware = swstats . getMiddleware ( { name : this . coreConfig ?. name , uriPath : this . coreConfig ?. obfPath ?? `/obf` , swaggerSpec : this . coreConfig ?. openapiSpec , authentication : this . coreConfig . authentication ?? false , onAuthenticate : this . coreConfig . swaggerAuthenticate ? this . coreConfig . swaggerAuthenticate : ( req , username , password ) => { return ( username === this . coreConfig . swaggerUsername && password === this . coreConfig . swaggerPassword ) ; } , } ) ; middlewares . push ( swStatsMiddleware ) ; } if ( this . coreConfig ?. configObject ) { configure ( { ... this . coreConfig . configObject , register : this . localeObj } ) ; } else { configure ( { locales : [ LocaleKey . en , LocaleKey . es , LocaleKey . ptBr , LocaleKey . ptPt , LocaleKey . esCo , ] , fallbacks : { [ LocaleKey . es ] : 'en' , [ LocaleKey . esCo ] : 'en' , [ LocaleKey . ptBr ] : 'en' , [ LocaleKey . ptPt ] : 'en' , } , register : this . localeObj , directoryPermissions : '777' , directory : `${ __dirname }/../locales` , objectNotation : '->' as any , } ) ; } this . application . bind ( SFCoreBindings . EXPRESS_MIDDLEWARES ) . to ( middlewares ) ; this . bindings . push ( Binding . bind ( OASBindings . HiddenEndpoint ) . to ( [ ] ) ) ; this . bindings . push ( Binding . bind ( SFCoreBindings . i18n ) . to ( this . localeObj ) ) ; this . application . add ( createBindingFromClass ( OperationSpecEnhancer ) ) ; } localeObj : i18nAPI = { } as i18nAPI ; providers ? : ProviderMap = { } ; bindings : Binding [ ] = [ ] ; }