Generic JSON file persistence plugin factory
(name: string, apiPath: string, filePath: string)
| 321 | |
| 322 | /** Generic JSON file persistence plugin factory */ |
| 323 | function jsonFilePlugin(name: string, apiPath: string, filePath: string): Plugin { |
| 324 | return { |
| 325 | name, |
| 326 | configureServer(server) { |
| 327 | server.middlewares.use(apiPath, (req, res) => { |
| 328 | res.setHeader('Content-Type', 'application/json'); |
| 329 | |
| 330 | if (req.method === 'GET') { |
| 331 | try { |
| 332 | if (fs.existsSync(filePath)) { |
| 333 | res.writeHead(200); |
| 334 | res.end(fs.readFileSync(filePath, 'utf-8')); |
| 335 | } else { |
| 336 | res.writeHead(200); |
| 337 | res.end('{}'); |
| 338 | } |
| 339 | } catch (err) { |
| 340 | res.writeHead(500); |
| 341 | res.end(JSON.stringify({ error: String(err) })); |
| 342 | } |
| 343 | return; |
| 344 | } |
| 345 | |
| 346 | if (req.method === 'POST') { |
| 347 | const chunks: Buffer[] = []; |
| 348 | req.on('data', (chunk: Buffer) => chunks.push(chunk)); |
| 349 | req.on('end', () => { |
| 350 | try { |
| 351 | const body = Buffer.concat(chunks).toString(); |
| 352 | JSON.parse(body); |
| 353 | fs.mkdirSync(resolve(os.homedir(), '.openroom'), { recursive: true }); |
| 354 | fs.writeFileSync(filePath, body, 'utf-8'); |
| 355 | res.writeHead(200); |
| 356 | res.end(JSON.stringify({ ok: true })); |
| 357 | } catch (err) { |
| 358 | res.writeHead(500); |
| 359 | res.end(JSON.stringify({ error: String(err) })); |
| 360 | } |
| 361 | }); |
| 362 | return; |
| 363 | } |
| 364 | |
| 365 | res.writeHead(405); |
| 366 | res.end(JSON.stringify({ error: 'Method not allowed' })); |
| 367 | }); |
| 368 | }, |
| 369 | }; |
| 370 | } |
| 371 | |
| 372 | const config = ({ mode }: ConfigEnv): UserConfigExport => { |
| 373 | const env = loadEnv(mode, process.cwd(), ''); |