81 lines
1.8 KiB
JavaScript
81 lines
1.8 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`)
|
||
|
|
}
|
||
|
|
|
||
|
|
function generateId() {
|
||
|
|
return Math.random().toString(36).substring(2, 15)
|
||
|
|
}
|
||
|
|
|
||
|
|
export default defineEventHandler(async (event) => {
|
||
|
|
const method = event.method
|
||
|
|
const collection = event.context.params?.collection
|
||
|
|
const id = event.context.params?.id
|
||
|
|
|
||
|
|
if (!collection) {
|
||
|
|
throw createError({ statusCode: 400, message: 'Collection 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 === 'GET') {
|
||
|
|
return readData()
|
||
|
|
}
|
||
|
|
|
||
|
|
if (method === 'POST') {
|
||
|
|
const body = await readBody(event)
|
||
|
|
const data = readData()
|
||
|
|
body.id = generateId()
|
||
|
|
data.push(body)
|
||
|
|
writeData(data)
|
||
|
|
return body
|
||
|
|
}
|
||
|
|
|
||
|
|
if (method === 'PUT') {
|
||
|
|
const body = await readBody(event)
|
||
|
|
const data = readData()
|
||
|
|
const index = data.findIndex(item => item.id === body.id)
|
||
|
|
if (index !== -1) {
|
||
|
|
data[index] = body
|
||
|
|
writeData(data)
|
||
|
|
}
|
||
|
|
return body
|
||
|
|
}
|
||
|
|
|
||
|
|
if (method === 'DELETE' && id) {
|
||
|
|
const data = readData()
|
||
|
|
const filtered = data.filter(item => item.id !== id)
|
||
|
|
writeData(filtered)
|
||
|
|
return { success: true }
|
||
|
|
}
|
||
|
|
|
||
|
|
throw createError({ statusCode: 405, message: 'Method not allowed' })
|
||
|
|
})
|