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
79 changes: 77 additions & 2 deletions src/createServer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,83 @@
'use strict';

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

function createServer() {
/* Write your code here */
// Return instance of http.Server class
const server = new http.Server();

server.on('request', (req, res) => {
if (req.url === '/' && req.method === 'GET') {
const filePath = path.resolve(__dirname, 'index.html');
const stream = fs.createReadStream(filePath);

stream.on('error', () => {
res.statusCode = 500;

return res.end('Cannot read index.html');
});

res.writeHead(200, { 'Content-Type': 'text/html' });

return stream.pipe(res);
}

if (req.method === 'POST' && req.url.startsWith('/add-expense')) {
const form = new formidable.IncomingForm({ multiples: false });

form.parse(req, (err, fields, files) => {
if (err) {
res.statusCode = 500;

return res.end('Error parsing the form');
}

const { date, title, amount } = fields || {};

if (!date || !title || !amount) {
res.statusCode = 400;

return res.end('Missing fields');
}

const filePath = path.resolve(__dirname, '../db/expense.json');
let expenses = [];

try {
const content = fs.readFileSync(filePath, 'utf-8').trim();

if (content) {
const parsed = JSON.parse(content);

if (Array.isArray(parsed)) {
expenses = parsed;
} else {
expenses = [];
}
}
} catch (e) {
expenses = [];
}

expenses.push({ date, title, amount });

fs.writeFileSync(filePath, JSON.stringify(expenses, null, 2));

res.writeHead(200, { 'Content-Type': 'text/html' });

return res.end(`<pre>${JSON.stringify(expenses)}</pre>`);
});

return;
}

res.statusCode = 404;
res.end('Not Found');
});

return server;
}

module.exports = {
Expand Down
19 changes: 19 additions & 0 deletions src/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="/add-expense"
method="POST"
enctype="multipart/form-data"
>
Comment on lines +9 to +12
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 form is set up correctly to send data. However, the backend logic in createServer.js that handles this submission has two issues that violate the task requirements:

  1. The db/expense.json file is overwritten on every submission, losing all previous data. It should accumulate expenses in an array.
  2. The server returns raw JSON, but the requirement is to return an 'HTML page with well formatted JSON'.

Please adjust the server-side code to fix these issues.

<input type="date" name="date" />
<input type="text" name="title"/>
<input type="number" name="amount" id="">
<button type="submit">Envoyer</button>
</form>
</body>
</html>
Loading