68 lines
1.9 KiB
TypeScript
68 lines
1.9 KiB
TypeScript
import { defineConfig } from 'vite'
|
|
import react from '@vitejs/plugin-react'
|
|
import fs from 'node:fs'
|
|
import path from 'node:path'
|
|
import type { IncomingMessage, ServerResponse } from 'node:http'
|
|
|
|
const DATA_FILE = path.resolve('./data.json')
|
|
|
|
function readData(): Record<string, unknown> {
|
|
if (!fs.existsSync(DATA_FILE)) return {}
|
|
try {
|
|
return JSON.parse(fs.readFileSync(DATA_FILE, 'utf-8'))
|
|
} catch {
|
|
return {}
|
|
}
|
|
}
|
|
|
|
function readBody(req: IncomingMessage): Promise<string> {
|
|
return new Promise((resolve) => {
|
|
let body = ''
|
|
req.on('data', (chunk: Buffer) => { body += chunk.toString() })
|
|
req.on('end', () => resolve(body))
|
|
})
|
|
}
|
|
|
|
export default defineConfig({
|
|
plugins: [
|
|
react(),
|
|
{
|
|
name: 'data-api',
|
|
configureServer(server) {
|
|
server.middlewares.use('/api/data', async (req: IncomingMessage, res: ServerResponse) => {
|
|
res.setHeader('Content-Type', 'application/json')
|
|
|
|
if (req.method === 'GET') {
|
|
const data = readData()
|
|
res.end(JSON.stringify(data))
|
|
|
|
} else if (req.method === 'POST') {
|
|
const body = await readBody(req)
|
|
const incoming = JSON.parse(body) as { key: string; value: unknown }
|
|
const data = readData()
|
|
data[incoming.key] = incoming.value
|
|
fs.writeFileSync(DATA_FILE, JSON.stringify(data))
|
|
res.end('{"ok":true}')
|
|
|
|
} else if (req.method === 'DELETE') {
|
|
const key = new URL(req.url ?? '', 'http://x').searchParams.get('key')
|
|
if (key) {
|
|
const data = readData()
|
|
delete data[key]
|
|
fs.writeFileSync(DATA_FILE, JSON.stringify(data))
|
|
}
|
|
res.end('{"ok":true}')
|
|
|
|
} else {
|
|
res.statusCode = 405
|
|
res.end('{"error":"Method Not Allowed"}')
|
|
}
|
|
})
|
|
},
|
|
},
|
|
],
|
|
server: {
|
|
host: true, // ローカルネットワーク全体に公開
|
|
},
|
|
})
|