import { SwaggerOptions , fastifySwagger } from 'fastify-swagger' ; import { EzApp , EzBackendOpts } from '@ezbackend/common' ; import type { FastifyRegisterOptions } from 'fastify' ; import { PluginScope } from '@ezbackend/core' ; import { merge } from 'lodash' ; declare module '@ezbackend/common' { interface EzBackendOpts { openAPI : FastifyRegisterOptions < SwaggerOptions > | undefined ; } } const defaultConfig = { prefix : '/docs' , routePrefix : '/docs' , exposeRoute : true , logLevel : 'warn' , openapi : { info : { title : 'EzBackend API' , description : 'Automatically generated documentation for EzBackend' , version : '1.0.0' , } , externalDocs : { url : 'https://github.com/kapydev/ezbackend' , description : 'Find more info here' , } , } , transform : ( schema ) => { const result = recursiveCustomPropertyReplacement ( schema ) ; return result ; } } ; function recursiveCustomPropertyReplacement ( schema ) { if ( typeof schema === 'object' ) { if ( schema . customSwaggerProps !== undefined ) { schema = merge ( { } , schema , schema . customSwaggerProps ) ; delete schema . customSwaggerProps ; } const fullyReplaced = Object . fromEntries ( Object . entries ( schema ) . map ( ( [ key , value ] ) => { if ( Object . prototype . toString . call ( value ) === '[object Object]' ) { return [ key , recursiveCustomPropertyReplacement ( value ) ] ; } return [ key , value ] ; } ) ) ; return fullyReplaced ; } else { return schema ; } } export class EzOpenAPI extends EzApp { constructor ( ) { super ( ) ; this . setDefaultOpts ( defaultConfig ) ; this . setHandler ( 'Add Swagger Plugin' , async ( instance , fullOpts ) => { const opts = this . getOpts ( 'openAPI' , fullOpts ) ; instance . server . register ( fastifySwagger , opts ) ; } ) ; this . scope = PluginScope . PARENT ; } }