From d622154035003be74c9432140fb441781627e052 Mon Sep 17 00:00:00 2001 From: VladSlob <141657806+VladSlob@users.noreply.github.com> Date: Wed, 1 Oct 2025 09:43:30 +0300 Subject: [PATCH 1/4] createServer.js --- src/createServer.js | 81 ++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 76 insertions(+), 5 deletions(-) diff --git a/src/createServer.js b/src/createServer.js index 1cf1dda..ddeb5c5 100644 --- a/src/createServer.js +++ b/src/createServer.js @@ -1,10 +1,81 @@ 'use strict'; +const http = require('http'); +const fs = require('fs'); +const path = require('path'); + +const DATA_PATH = path.resolve('db', 'expense.json'); + function createServer() { - /* Write your code here */ - // Return instance of http.Server class + return http.createServer((req, res) => { + const indexPath = path.resolve('src', 'index.html'); + + + if (req.method === 'GET' && req.url === '/') { + try { + const file = fs.readFileSync(indexPath); + + res.writeHead(200, { 'Content-Type': 'text/html' }); + res.end(file); + } catch { + res.writeHead(404, { 'Content-Type': 'text/plain' }); + res.end('file not found'); + } + + return; + } + + + if (req.method === 'POST' && req.url === '/add-expense') { + const chunks = []; + + req.on('data', (chunk) => chunks.push(chunk)); + + req.on('end', () => { + try { + const buffer = Buffer.concat(chunks).toString(); + const obj = JSON.parse(buffer); + + if (!obj.date || !obj.title || !obj.amount) { + res.writeHead(400, { 'Content-Type': 'text/plain' }); + res.end('Invalid expense data'); + + return; + } + + + fs.writeFileSync(DATA_PATH, JSON.stringify(obj, null, 2)); + + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify(obj)); + } catch { + res.writeHead(400, { 'Content-Type': 'text/plain' }); + res.end('Invalid JSON'); + } + }); + + return; + } + if (req.method === 'GET' && req.url === '/expenses') { + try { + const data = fs.existsSync(DATA_PATH) + ? fs.readFileSync(DATA_PATH, 'utf-8') + : ''; + const obj = data ? JSON.parse(data) : {}; + + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify(obj)); + } catch { + res.writeHead(500, { 'Content-Type': 'text/plain' }); + res.end('Failed to read expense'); + } + + return; + } + + res.writeHead(404, { 'Content-Type': 'text/plain' }); + res.end('Not found'); + }); } -module.exports = { - createServer, -}; +module.exports = { createServer }; From aef0e3e96940b860c327368e94f4d5ef8e5a37db Mon Sep 17 00:00:00 2001 From: VladSlob <141657806+VladSlob@users.noreply.github.com> Date: Wed, 1 Oct 2025 09:44:00 +0300 Subject: [PATCH 2/4] index.html --- src/index.html | 55 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 src/index.html diff --git a/src/index.html b/src/index.html new file mode 100644 index 0000000..5617a60 --- /dev/null +++ b/src/index.html @@ -0,0 +1,55 @@ + + +
+ +