Skip to content
Open
Changes from 1 commit
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
43 changes: 41 additions & 2 deletions src/createServer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,47 @@
'use strict';

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

function createServer() {
/* Write your code here */
// Return instance of http.Server class
return http.createServer((request, response) => {
if (request.url === '/add-expense' && request.method === 'POST') {
const chunks = [];

request.on('data', (chunk) => {
chunks.push(chunk);
});

request.on('end', () => {
try {
const parsedData = JSON.parse(Buffer.concat(chunks).toString());

if (!parsedData.amount || !parsedData.title || !parsedData.date) {
response.statusCode = 400;
response.end('Invalid data');

return;
}

const db = path.join(__dirname, '../db/expense.json');
const stringifiedData = JSON.stringify(parsedData);

fs.writeFileSync(db, stringifiedData);
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 implementation overwrites the expense.json file with every new request. As a result, only the last submitted expense will be saved. To store all expenses, you should first read the existing content of the file, parse it as an array, add the new expense object to that array, and then write the updated array back to the file.


response.statusCode = 200;
response.setHeader('Content-Type', 'application/json');
response.end(JSON.stringify(parsedData));
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 task requires returning an HTML page that contains the JSON data. Currently, you are sending a response with the Content-Type set to application/json and a raw JSON string as the body. You should set the content type to text/html and wrap the JSON string in basic HTML tags, like <pre>, to display it correctly on a page.

} catch {
response.statusCode = 400;
response.end('Invalid data');
}
});
} else {
response.statusCode = 404;
response.end('Not Found');
}
});
}

module.exports = {
Expand Down
Loading