import { swaggerConfig } from './swagger'; // HTML template for Swagger UI const swaggerHtml = ` API Documentation
`; /** * Handles Swagger UI requests * @param {Request} request - The incoming request * @param {string} basePath - The base path for the API * @returns {Response} - The response with Swagger UI or JSON */ export function handleSwaggerRequest(request, basePath = '') { try { const url = new URL(request.url); const path = url.pathname; // Serve the OpenAPI/Swagger JSON specification if (path === `${basePath}/openapi.json` || path === `${basePath}/swagger.json`) { return new Response(JSON.stringify(swaggerConfig), { headers: { 'Content-Type': 'application/json' }, }); } // Serve the Swagger UI HTML if (path === `${basePath}/docs` || path === `${basePath}/docs/` || path === basePath) { // Replace the placeholder with the actual Swagger definition const html = swaggerHtml.replace( 'SWAGGER_SPEC', JSON.stringify(swaggerConfig) ); return new Response(html, { headers: { 'Content-Type': 'text/html' }, }); } // If not a valid Swagger UI path, return a JSON error return new Response(JSON.stringify({ error: 'Not Found', message: 'The requested Swagger UI resource was not found' }), { status: 404, headers: { 'Content-Type': 'application/json' } }); } catch (error) { // Return a proper JSON error response instead of HTML return new Response(JSON.stringify({ error: 'Swagger UI Error', details: error.message }), { status: 500, headers: { 'Content-Type': 'application/json' } }); } }