diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..4a5cdc9 --- /dev/null +++ b/public/index.html @@ -0,0 +1,155 @@ + + + + + + + Document + + + + +
+

💰Expense Tracker

+

Додайте нову витрату

+ +
+
+ + +
+ +
+ + +
+ +
+ + +
+ + +
+
+ + + \ No newline at end of file diff --git a/src/createServer.js b/src/createServer.js index 1cf1dda..6d88c03 100644 --- a/src/createServer.js +++ b/src/createServer.js @@ -1,8 +1,85 @@ 'use strict'; +const http = require('http'); +const path = require('path'); +const fs = require('fs'); +const querystring = require('querystring'); + +const dataPath = path.resolve(__dirname, '..', 'db', 'expense.json'); +const htmlPath = path.resolve(__dirname, '..', 'public', 'index.html'); + function createServer() { - /* Write your code here */ - // Return instance of http.Server class + return http.createServer((req, res) => { + if (req.method === 'GET' && req.url === '/') { + fs.readFile(htmlPath, (err, data) => { + if (err) { + res.writeHead(500); + + return res.end('Error loading index.html'); + } + res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); + res.end(data); + }); + + return; + } + + if (req.method === 'POST' && req.url === '/add-expense') { + let body = ''; + + req.on('data', (chunk) => { + body += chunk.toString(); + }); + + req.on('end', () => { + try { + const contentType = req.headers['content-type']; + const isJsonRequest = + contentType && contentType.startsWith('application/json'); + + const expense = isJsonRequest + ? JSON.parse(body) + : querystring.parse(body); + + if (!expense.date || !expense.title || !expense.amount) { + res.writeHead(400, { 'Content-Type': 'text/plain' }); + + return res.end('Missing fields'); + } + + const prettyJson = JSON.stringify(expense, null, 2); + + fs.writeFileSync(dataPath, prettyJson); + + if (isJsonRequest) { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify(expense)); + } else { + const responseHtml = ` + + + + +
${prettyJson}
+ + + `; + + res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); + res.end(responseHtml); + } + } catch (error) { + res.writeHead(400); + res.end('Invalid Data'); + } + }); + + return; + } + + res.writeHead(404); + res.end('Not Found'); + }); } module.exports = {