import { NestFastifyApplication } from '@nestjs/platform-fastify'; import { OpenAPIObject, SwaggerModule } from '@nestjs/swagger'; import { readFileSync } from 'fs'; import { join } from 'path'; import { GUIDE, OPERATION_EXAMPLES } from './examples'; const CONTRACT_PATH = join(process.cwd(), 'contracts', 'openapi.json'); export function setupSwagger(app: NestFastifyApplication): void { SwaggerModule.setup('docs', app, loadDocument(), { customSiteTitle: 'Messenger lab5 API', swaggerOptions: { persistAuthorization: true, displayRequestDuration: true, tryItOutEnabled: true, }, }); } export function loadDocument(): OpenAPIObject { const document = JSON.parse(readFileSync(CONTRACT_PATH, 'utf8')); document.info.description = GUIDE; document.servers = [{ url: '/', description: 'Этот экземпляр API' }]; for (const [key, examples] of Object.entries(OPERATION_EXAMPLES)) { const [method, path] = key.split(' '); const operation = document.paths[path]?.[method.toLowerCase()]; if (!operation) { throw new Error(`examples for unknown operation ${key}`); } if (examples.request) { operation.requestBody.content['application/json'].examples = examples.request; } for (const [status, named] of Object.entries(examples.responses)) { const content = operation.responses[status]?.content; if (!content) { throw new Error(`examples for unknown response ${key} ${status}`); } content['application/json'].examples = named; } } return document; }