109 lines
2.9 KiB
JavaScript
109 lines
2.9 KiB
JavaScript
import fs from 'fs'
|
|
import path from 'path'
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
try {
|
|
const body = await readBody(event)
|
|
const { content, filename = 'openapi-custom.json', sourceType = 'custom' } = body
|
|
|
|
if (!content) {
|
|
throw createError({
|
|
statusCode: 400,
|
|
statusMessage: 'Content is required'
|
|
})
|
|
}
|
|
|
|
// Validate that content is valid JSON
|
|
let parsedContent
|
|
try {
|
|
if (typeof content === 'string') {
|
|
parsedContent = JSON.parse(content)
|
|
} else {
|
|
parsedContent = content
|
|
}
|
|
} catch (error) {
|
|
throw createError({
|
|
statusCode: 400,
|
|
statusMessage: 'Invalid JSON content: ' + error.message
|
|
})
|
|
}
|
|
|
|
// Ensure docs directory exists
|
|
const docsDir = path.join(process.cwd(), 'docs')
|
|
if (!fs.existsSync(docsDir)) {
|
|
fs.mkdirSync(docsDir, { recursive: true })
|
|
}
|
|
|
|
// Determine the correct filename based on source type
|
|
let cleanFilename
|
|
if (sourceType === 'collections') {
|
|
cleanFilename = 'openapi-collection.json'
|
|
} else if (sourceType === 'custom') {
|
|
cleanFilename = 'openapi-custom.json'
|
|
} else {
|
|
// Clean the provided filename
|
|
cleanFilename = filename.replace(/[^a-zA-Z0-9.-]/g, '_')
|
|
if (!cleanFilename.endsWith('.json')) {
|
|
cleanFilename += '.json'
|
|
}
|
|
}
|
|
|
|
// Validate OpenAPI structure
|
|
if (!parsedContent.openapi) {
|
|
throw createError({
|
|
statusCode: 400,
|
|
statusMessage: 'Invalid OpenAPI specification: missing "openapi" field'
|
|
})
|
|
}
|
|
|
|
if (!parsedContent.info) {
|
|
throw createError({
|
|
statusCode: 400,
|
|
statusMessage: 'Invalid OpenAPI specification: missing "info" field'
|
|
})
|
|
}
|
|
|
|
// Write file with formatted JSON
|
|
const filePath = path.join(docsDir, cleanFilename)
|
|
const formattedContent = JSON.stringify(parsedContent, null, 2)
|
|
fs.writeFileSync(filePath, formattedContent, 'utf-8')
|
|
|
|
// Determine the API URL based on the filename
|
|
let apiUrl
|
|
if (cleanFilename === 'openapi-collection.json') {
|
|
apiUrl = '/openapi-coll.json'
|
|
} else if (cleanFilename === 'openapi-custom.json') {
|
|
apiUrl = '/openapi-custom.json'
|
|
} else {
|
|
apiUrl = `/docs/${cleanFilename}`
|
|
}
|
|
|
|
return {
|
|
statusCode: 200,
|
|
message: 'OpenAPI specification saved successfully',
|
|
data: {
|
|
filename: cleanFilename,
|
|
path: `/docs/${cleanFilename}`,
|
|
apiUrl: apiUrl,
|
|
sourceType: sourceType,
|
|
size: Buffer.byteLength(formattedContent, 'utf-8')
|
|
}
|
|
}
|
|
|
|
} catch (error) {
|
|
console.error('Error saving OpenAPI file:', error)
|
|
|
|
// If it's already a createError, re-throw it
|
|
if (error.statusCode) {
|
|
throw error
|
|
}
|
|
|
|
throw createError({
|
|
statusCode: 500,
|
|
statusMessage: 'Failed to save file',
|
|
data: {
|
|
error: error.message
|
|
}
|
|
})
|
|
}
|
|
})
|