diff --git a/src/createServer.js b/src/createServer.js
index 1cf1dda..6f18625 100644
--- a/src/createServer.js
+++ b/src/createServer.js
@@ -1,8 +1,137 @@
'use strict';
+const http = require('http');
+const fs = require('fs');
+const path = require('path');
+const querystring = require('querystring');
+
function createServer() {
- /* Write your code here */
- // Return instance of http.Server class
+ return http.createServer((req, res) => {
+ if (req.method === 'GET' && req.url === '/') {
+ res.writeHead(200, {
+ 'Content-Type': 'text/html',
+ });
+
+ res.end(`
+
+
+
+
+ Add expense
+
+
+ Add expense
+
+
+
+
+ `);
+
+ return;
+ }
+
+ if (req.method === 'POST' && req.url === '/add-expense') {
+ let body = '';
+
+ req.on('data', (chunk) => {
+ body += chunk.toString();
+ });
+
+ req.on('end', () => {
+ const contentType = req.headers['content-type'] || '';
+ let expense = {};
+
+ try {
+ if (contentType.includes('application/json')) {
+ expense = JSON.parse(body);
+ } else {
+ expense = querystring.parse(body);
+ }
+ } catch (error) {
+ res.writeHead(400, {
+ 'Content-Type': 'text/plain',
+ });
+ res.end('Invalid request body');
+
+ return;
+ }
+
+ const { date, title, amount } = expense;
+
+ if (!date || !title || !amount) {
+ res.writeHead(400, {
+ 'Content-Type': 'text/plain',
+ });
+ res.end('Missing required fields');
+
+ return;
+ }
+
+ const dataPath = path.resolve(__dirname, '../db/expense.json');
+
+ fs.writeFileSync(dataPath, JSON.stringify({ date, title, amount }));
+
+ if (contentType.includes('application/json')) {
+ res.writeHead(200, {
+ 'Content-Type': 'application/json',
+ });
+ res.end(JSON.stringify({ date, title, amount }));
+
+ return;
+ }
+
+ res.writeHead(200, {
+ 'Content-Type': 'text/html',
+ });
+
+ res.end(`
+
+
+
+
+ Expense saved
+
+
+ Expense saved
+ ${escapeHtml(JSON.stringify({ date, title, amount }, null, 2))}
+ Back
+
+
+ `);
+ });
+
+ return;
+ }
+
+ res.writeHead(404, {
+ 'Content-Type': 'text/plain',
+ });
+ res.end('Page not found');
+ });
+}
+
+function escapeHtml(text) {
+ return text
+ .replaceAll('&', '&')
+ .replaceAll('<', '<')
+ .replaceAll('>', '>');
}
module.exports = {