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

101 lines
3.2 KiB
JavaScript

import fs from 'fs'
import path from 'path'
export default defineEventHandler(async (event) => {
try {
console.log('Original OpenAPI JSON endpoint called')
// Set appropriate headers for JSON response and CORS
setHeader(event, 'Content-Type', 'application/json')
setHeader(event, 'Cache-Control', 'no-cache') // Disable caching for development
// Add CORS headers
setHeader(event, 'Access-Control-Allow-Origin', '*')
setHeader(event, 'Access-Control-Allow-Methods', 'GET, OPTIONS')
setHeader(event, 'Access-Control-Allow-Headers', 'Content-Type, Authorization')
// Handle OPTIONS request for CORS preflight
if (event.node.req.method === 'OPTIONS') {
return {}
}
console.log('Serving OpenAPI JSON...')
// Read the main OpenAPI JSON file
const openApiPath = path.join(process.cwd(), 'docs', 'openapi.json')
console.log(`Looking for OpenAPI file at: ${openApiPath}`)
if (!fs.existsSync(openApiPath)) {
console.error(`OpenAPI specification file not found at: ${openApiPath}`)
throw createError({
statusCode: 404,
statusMessage: 'OpenAPI specification not found'
})
}
console.log(`OpenAPI file exists, reading content...`)
const openApiContent = fs.readFileSync(openApiPath, 'utf-8')
let openApiSpec
try {
openApiSpec = JSON.parse(openApiContent)
console.log('Successfully parsed OpenAPI JSON')
} catch (parseError) {
console.error(`Failed to parse OpenAPI JSON: ${parseError.message}`)
throw createError({
statusCode: 500,
statusMessage: 'Invalid OpenAPI JSON format',
data: { error: parseError.message }
})
}
// 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]
console.log(`Successfully serving OpenAPI spec from ${openApiPath}`)
return openApiSpec
} catch (error) {
console.error('Error serving OpenAPI specification:', error)
throw createError({
statusCode: error.statusCode || 500,
statusMessage: error.statusMessage || 'Failed to load OpenAPI specification',
data: {
error: error.message
}
})
}
})