99 lines
2.8 KiB
JavaScript
99 lines
2.8 KiB
JavaScript
import fs from 'fs'
|
|
import path from 'path'
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
try {
|
|
// Set 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 {}
|
|
}
|
|
|
|
// Get file path from URL safely
|
|
let filePath = '';
|
|
if (event.context.params && event.context.params._) {
|
|
filePath = Array.isArray(event.context.params._)
|
|
? event.context.params._.join('/')
|
|
: event.context.params._.toString();
|
|
}
|
|
|
|
console.log(`Requested docs file: ${filePath}`)
|
|
|
|
// Full path to file
|
|
const fullPath = path.join(process.cwd(), 'docs', filePath)
|
|
|
|
// Check if file exists
|
|
if (!fs.existsSync(fullPath)) {
|
|
console.error(`File not found: ${fullPath}`)
|
|
throw createError({
|
|
statusCode: 404,
|
|
statusMessage: `File not found: ${filePath}`
|
|
})
|
|
}
|
|
|
|
// Determine content type based on file extension
|
|
const ext = path.extname(fullPath).toLowerCase()
|
|
let contentType = 'text/plain'
|
|
|
|
switch (ext) {
|
|
case '.json':
|
|
contentType = 'application/json'
|
|
break
|
|
case '.md':
|
|
contentType = 'text/markdown'
|
|
break
|
|
case '.yaml':
|
|
case '.yml':
|
|
contentType = 'application/x-yaml'
|
|
break
|
|
case '.html':
|
|
contentType = 'text/html'
|
|
break
|
|
case '.css':
|
|
contentType = 'text/css'
|
|
break
|
|
case '.js':
|
|
contentType = 'application/javascript'
|
|
break
|
|
case '.png':
|
|
contentType = 'image/png'
|
|
break
|
|
case '.jpg':
|
|
case '.jpeg':
|
|
contentType = 'image/jpeg'
|
|
break
|
|
}
|
|
|
|
// Set headers
|
|
setHeader(event, 'Content-Type', contentType)
|
|
setHeader(event, 'Cache-Control', 'no-cache') // Disable caching for development
|
|
|
|
// For JSON files, we need to validate and potentially parse
|
|
if (ext === '.json') {
|
|
try {
|
|
const content = fs.readFileSync(fullPath, 'utf-8')
|
|
return JSON.parse(content)
|
|
} catch (error) {
|
|
console.error(`Error parsing JSON file: ${error.message}`)
|
|
throw createError({
|
|
statusCode: 500,
|
|
statusMessage: `Invalid JSON file: ${error.message}`
|
|
})
|
|
}
|
|
}
|
|
|
|
// For other files, return the raw content
|
|
return fs.readFileSync(fullPath)
|
|
} catch (error) {
|
|
console.error(`Error serving docs file: ${error.message}`)
|
|
throw createError({
|
|
statusCode: error.statusCode || 500,
|
|
statusMessage: error.message || 'Failed to serve file',
|
|
data: { error: error.message }
|
|
})
|
|
}
|
|
})
|