import swaggerUi from 'swagger-ui-express' import path from 'node:path' export namespace Internals { export async function loadSwaggerConfig(): Promise { const obj = require('@@/swagger/header.json') obj.paths = Object.create(null) const swaggerFolder = path.join( Plata.ProjectDir, '__BUILD__', 'swagger', 'routes' ).replace(/\\/g, '/') // build routes { const routes = await Plata.files.FindFiles([ swaggerFolder ], 'header.json') for (const route of routes) { const docPath = path.normalize(path.dirname(route)) const method = path.normalize(path.basename(docPath)) const httpPath = path.normalize( path.dirname(docPath.replace(/\\/g, '/').replace(swaggerFolder, '')) ).replace(/\\/g, '/') const header = require(path.join(docPath, 'header.json')) const body = require(path.join(docPath, 'body.json')) const response = require(path.join(docPath, 'response.json')) if (obj.paths[httpPath] === undefined) { obj.paths[httpPath] = Object.create(null) } obj.paths[httpPath][method] = { ...header, responses: response } //https://bobbyhadz.com/blog/javascript-check-if-object-is-empty if (Object.keys(body).length !== 0) { if (!Array.isArray(obj.paths[httpPath][method].parameters)) { obj.paths[httpPath][method].parameters = [] } const swaggerRouteBody = { name: "body", description: body.description, in: "body", schema: { ...body.extras, type: body.type ?? "object", } } as any if (swaggerRouteBody.schema.type === 'array') { swaggerRouteBody.schema.items = { example: body.example } } else { swaggerRouteBody.schema.properties = body.example } obj.paths[httpPath][method].parameters.push(swaggerRouteBody) } } } return obj } } export const swagger: Router.RouterBuilder = async (router) => { router.swaggerHide = true if (Plata.config._PLATA_WORKER_NAME === '__PLATA_EXPRESS__') { router.use( swaggerUi.serve as any, swaggerUi.setup( await Internals.loadSwaggerConfig(), {} ) as any ) } return router }