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
103 changes: 101 additions & 2 deletions src/createServer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,107 @@
'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 raw = fs.readFileSync(filePath, 'utf8');
// const arr = JSON.parse(raw);
const record = {
date: expenseData.date,
title: expenseData.title,
amount: expenseData.amount,
};

// arr.push(record);

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 {}.


res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(expenseData));
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 requirement is to return an HTML page containing well-formatted JSON. This implementation sends a raw JSON response with the Content-Type set to application/json. You should change the Content-Type to text/html and wrap the JSON string in HTML tags (e.g., <pre>) to display it correctly on a web page.

}
});
}
}
});
}

module.exports = {
Expand Down
Loading