portfolio/server/api/admin/[collection].js

82 lines
1.8 KiB
JavaScript

import { readFileSync, writeFileSync, existsSync } from 'node:fs'
import { join } from 'node:path'
import { nanoid } from 'nanoid'
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 nanoid(12)
}
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' })
})