corrad-af-2024/server/api/openapi-coll.json.get.js

72 lines
2.2 KiB
JavaScript

import fs from 'fs'
import path from 'path'
export default defineEventHandler(async (event) => {
try {
// Set appropriate headers for JSON response
setHeader(event, 'Content-Type', 'application/json')
setHeader(event, 'Cache-Control', 'public, max-age=300') // Cache for 5 minutes
// Read the collections OpenAPI JSON file
const openApiPath = path.join(process.cwd(), 'docs', 'openapi-collection.json')
if (!fs.existsSync(openApiPath)) {
throw createError({
statusCode: 404,
statusMessage: 'Collections OpenAPI specification not found. Please generate it first from the configuration panel.'
})
}
const openApiContent = fs.readFileSync(openApiPath, 'utf-8')
const openApiSpec = JSON.parse(openApiContent)
// Dynamically update server URLs based on the current request
const host = getHeader(event, 'host') || 'localhost:3000'
const protocol = getHeader(event, 'x-forwarded-proto') ||
(host.includes('localhost') || host.includes('127.0.0.1') ? 'http' : 'https')
// Update servers in the OpenAPI spec
openApiSpec.servers = [
{
url: `${protocol}://${host}/api`,
description: 'Current Server'
},
{
url: "http://localhost:3000/api",
description: "Development Server"
},
{
url: "{protocol}://{host}:{port}/api",
description: "Configurable Server",
variables: {
protocol: {
enum: ["http", "https"],
default: protocol
},
host: {
default: host.split(':')[0]
},
port: {
default: host.includes(':') ? host.split(':')[1] : (protocol === 'https' ? '443' : '80')
}
}
}
]
// Add current timestamp to info for cache busting
openApiSpec.info.version = openApiSpec.info.version + '+' + new Date().toISOString().split('T')[0]
return openApiSpec
} catch (error) {
console.error('Error serving Collections OpenAPI specification:', error)
throw createError({
statusCode: 500,
statusMessage: 'Failed to load Collections OpenAPI specification',
data: {
error: error.message
}
})
}
})