Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 107 additions & 2 deletions src/createServer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,113 @@
'use strict';

const http = require('http');
const fs = require('fs');

const form = `
<form method="POST" action="/add-expense">
<input
type="date"
name="date"
required
>
<input
type="text"
name="title"
placeholder="Enter title"
required
>
<input
type="number"
name="amount"
placeholder="Enter amount"
required
>
<button type="submit">Send</button>
</form>
`;

function createServer() {
/* Write your code here */
// Return instance of http.Server class
return http.createServer((req, res) => {
if (req.method === 'GET') {
if (req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(form);
} else if (req.url === '/add-expense') {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('Incorrect request');
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Page not found');
}

return;
}

if (req.method === 'POST') {
if (req.url === '/add-expense') {
let body = '';

req.on('data', (chunk) => (body += chunk));

req.on('end', () => {
let expenseData;

if (req.headers['content-type'] === 'application/json') {
expenseData = JSON.parse(body);
} else {
const params = new URLSearchParams(body);

expenseData = Object.fromEntries(params);
}

const dateObj = new Date(expenseData.date);
const isValidDate = dateObj instanceof Date && !isNaN(dateObj);

const isValidTitle =
expenseData.title && expenseData.title.trim().length > 0;

const amount = parseFloat(expenseData.amount);
const isValidAmount = !isNaN(amount) && amount > 0;

if (!isValidDate || !isValidTitle || !isValidAmount) {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('Invalid data');
} else {
const filePath = 'db/expense.json';

if (!fs.existsSync('db')) {
fs.mkdirSync('db');
}

if (!fs.existsSync(filePath)) {
fs.writeFileSync(filePath, JSON.stringify([]));
}

const record = {
date: expenseData.date,
title: expenseData.title,
amount: expenseData.amount,
};

fs.writeFileSync(filePath, JSON.stringify(record, null, 2));
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The current implementation overwrites the expense.json file with only the latest record. To meet the requirement of saving the expense data, you should append new expenses to the existing list. This typically involves reading the file, parsing the JSON into an array, adding the new record, and then writing the updated array back to the file.

Also, consider what the initial content of the file should be on line 83. If you plan to store a list of expenses, an empty array [] would be more suitable than an empty object {}.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line overwrites the file with only the new record. According to the requirements, you need to accumulate expenses. The correct logic would be to read the file, parse the JSON array, push the new record into it, and then write the entire updated array back to the file.


if (req.headers['content-type'] === 'application/json') {
// JSON запит — повертай JSON
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(record));
} else {
// HTML форма — повертай HTML
res.writeHead(200, { 'Content-Type': 'text/html' });

const html = `<pre>${JSON.stringify(record, null, 2)}</pre>`;

res.end(html);
}
}
});
}
}
});
}

module.exports = {
Expand Down
Loading