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
100 changes: 95 additions & 5 deletions src/createServer.js
Original file line number Diff line number Diff line change
@@ -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(`
<!doctype html>
<html lang="en">
<head><meta charset="UTF-8" /><title>Add Expense</title></head>
<body>
<form method="POST" action="/add-expense">
<input type="date" name="date" required />
<input type="text" name="title" placeholder="Title" required />
<input type="text" name="amount" placeholder="Amount" required />
<button type="submit">Submit</button>
</form>
</body>
</html>
`);

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) => {

Choose a reason for hiding this comment

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

This line is overwriting the contents of expense.json with only the new expense. The requirement is to append the new data.

To fix this, you should first parse the data (from line 58) which contains the existing expenses, push the new expense into that array, and then write the entire updated array back to the file.

Choose a reason for hiding this comment

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

You've correctly read the existing file content into the data variable. The next step is to parse this data into an array, add the new expense to it, and then write the entire updated array back to the file. Currently, you are only writing the new expense, which overwrites all existing data.

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));
Comment on lines +83 to +85

Choose a reason for hiding this comment

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

The response for a successful POST should be an HTML page that displays all the saved expenses. The requirements specify setting the Content-Type to text/html and wrapping the complete JSON data (the entire array of expenses) in <pre> tags.

});
});
});

return;
}

res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not found');
});

return server;
}

module.exports = {
createServer,
};
module.exports = { createServer };