diff --git a/src/createServer.js b/src/createServer.js index 1cf1dda..b7a025a 100644 --- a/src/createServer.js +++ b/src/createServer.js @@ -1,10 +1,100 @@ +/* eslint-disable no-console */ 'use strict'; +const { Server } = require('http'); +const fs = require('fs'); +const path = require('path'); + +const dbPath = path.resolve(__dirname, '../db/expense.json'); + function createServer() { - /* Write your code here */ - // Return instance of http.Server class + // створюємо файл, якщо його немає + if (!fs.existsSync(dbPath)) { + fs.writeFileSync(dbPath, JSON.stringify([]), 'utf8'); + } + + const server = new Server(); + + server.on('request', (req, res) => { + // GET /add-expense - HTML форма + if (req.url === '/add-expense' && req.method === 'GET') { + res.writeHead(200, { 'Content-Type': 'text/html' }); + + res.end(` + + + Add Expense + +
+ + + + +
+ + + `); + + return; + } + + // POST /add-expense - додаємо новий запис + if (req.url === '/add-expense' && req.method === 'POST') { + const bodyChunks = []; + + req.on('data', (chunk) => bodyChunks.push(chunk)); + + req.on('end', () => { + const json = Buffer.concat(bodyChunks); + let expense; + + try { + expense = JSON.parse(json.toString()); + } catch { + res.writeHead(400, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'Invalid JSON' })); + + return; + } + + if (!expense?.date || !expense?.title || !expense?.amount) { + res.statusCode = 400; + res.end('Bad user input'); + + return; + } + + fs.readFile(dbPath, 'utf8', (err, data) => { + if (err) { + res.writeHead(500, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'Read error' })); + + return; + } + + fs.writeFile(dbPath, JSON.stringify(expense, null, 2), (error) => { + if (error) { + res.writeHead(500, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'Write error' })); + + return; + } + + res.writeHead(200, { 'Content-Type': 'application/json' }); + + res.end(JSON.stringify(expense)); + }); + }); + }); + + return; + } + + res.writeHead(404, { 'Content-Type': 'text/plain' }); + res.end('Not found'); + }); + + return server; } -module.exports = { - createServer, -}; +module.exports = { createServer };