Skip to content
Open
Show file tree
Hide file tree
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
98 changes: 96 additions & 2 deletions src/createServer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,102 @@
'use strict';

const http = require('http');
const fs = require('fs/promises');
const path = require('path');

function readBody(req) {
return new Promise((resolve, reject) => {
let body = '';

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

if (body.length > 1e6) {
req.destroy();
reject(new Error('Body too large'));
}
});

req.on('end', () => resolve(body));
req.on('error', reject);
});
}

function parseExpense(req, body) {
const type = req.headers['content-type'] || '';

if (type.includes('application/json')) {
const data = JSON.parse(body || '{}');

return {
date: data.date || '',
title: data.title || '',
amount: data.amount || '',
};
}

const params = new URLSearchParams(body);

return {
date: params.get('date') || '',
title: params.get('title') || '',
amount: params.get('amount') || '',
};
}

function isValidExpense(expense) {
return expense.date && expense.title && expense.amount;
}

function createServer() {
/* Write your code here */
// Return instance of http.Server class
return http.createServer(async (req, res) => {
if (req.method === 'GET' && req.url === '/') {
const htmlPath = path.join(__dirname, '..', 'index.html');

const html = await fs.readFile(htmlPath, 'utf-8');

res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(html);

return;
}

if (
req.method === 'POST' &&
(req.url === '/add-expense' || req.url === '/submit-expense')
) {
try {
const body = await readBody(req);
const expense = parseExpense(req, body);

if (!isValidExpense(expense)) {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('Bad request');

return;
}

const dbDir = path.join(__dirname, '..', 'db');
const filePath = path.join(dbDir, 'expense.json');

await fs.mkdir(dbDir, { recursive: true });
await fs.writeFile(filePath, JSON.stringify(expense, null, 2), 'utf-8');

res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(expense));
Comment on lines +85 to +86

Choose a reason for hiding this comment

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

The task requires you to 'return an HTML page with well formatted JSON'. Currently, you are sending a raw JSON response with Content-Type: application/json. You should set the Content-Type to text/html and send an HTML document that displays the formatted JSON. A good way to display pre-formatted text like JSON in HTML is by using the <pre> tag.

Comment on lines +85 to +86

Choose a reason for hiding this comment

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

According to the task requirements, after saving the data, the server must return an HTML page that displays the saved data as well-formatted JSON.

Currently, you are returning a raw JSON response. You should change the Content-Type header to text/html and wrap the JSON string within an HTML structure. Using a <pre> tag is a good way to preserve the JSON formatting.

Comment on lines +85 to +86

Choose a reason for hiding this comment

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

The task requires the server to return an HTML page after saving the data, not a raw JSON response. The Content-Type header should be text/html, and the response body needs to be an HTML document that includes the formatted JSON.


return;
} catch {
res.writeHead(500);
res.end();

return;
}
}

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

module.exports = {
Expand Down
17 changes: 17 additions & 0 deletions src/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Expense form</title>
</head>
<body>
<h1>Add expense</h1>

<form method="POST" action="/add-expense">
<input type="date" name="date" required />
<input type="text" name="title" required />
<input type="number" name="amount" required />
<button type="submit">Save</button>
</form>
</body>
</html>