53 lines
1.3 KiB
JavaScript
53 lines
1.3 KiB
JavaScript
import { readFileSync, writeFileSync, existsSync } from 'node:fs'
|
|
import { join } from 'node:path'
|
|
|
|
const dataDir = './server/data'
|
|
|
|
function getFilePath(collection) {
|
|
const fileMap = {
|
|
works: 'works.json',
|
|
publications: 'publications.json',
|
|
events: 'events.json',
|
|
releases: 'releases.json',
|
|
talks: 'talks.json'
|
|
}
|
|
return join(dataDir, fileMap[collection] || `${collection}.json`)
|
|
}
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
const method = event.method
|
|
const collection = event.context.params?.collection
|
|
const id = event.context.params?.id
|
|
|
|
if (!collection || !id) {
|
|
throw createError({ statusCode: 400, message: 'Collection and ID required' })
|
|
}
|
|
|
|
const filePath = getFilePath(collection)
|
|
|
|
if (!existsSync(filePath)) {
|
|
throw createError({ statusCode: 404, message: 'Collection not found' })
|
|
}
|
|
|
|
const readData = () => {
|
|
try {
|
|
return JSON.parse(readFileSync(filePath, 'utf-8'))
|
|
} catch {
|
|
return []
|
|
}
|
|
}
|
|
|
|
const writeData = (data) => {
|
|
writeFileSync(filePath, JSON.stringify(data, null, 2))
|
|
}
|
|
|
|
if (method === 'DELETE') {
|
|
const data = readData()
|
|
const filtered = data.filter(item => item.id !== id)
|
|
writeData(filtered)
|
|
return { success: true }
|
|
}
|
|
|
|
throw createError({ statusCode: 405, message: 'Method not allowed' })
|
|
})
|