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
86 changes: 84 additions & 2 deletions src/createServer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,90 @@
'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 === '/' && request.method === 'GET') {
const htmlPath = path.resolve(__dirname, 'index.html');

fs.readFile(htmlPath, 'utf-8', (error, data) => {
if (error) {
response.statusCode = 500;
response.end('Internal Server Error');

return;
}

response.statusCode = 200;
response.setHeader('Content-Type', 'text/html');
response.end(data);
});
} else if (request.url === '/add-expense' && request.method === 'POST') {
const chunks = [];

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

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

const contentType = request.headers['content-type'] || '';

if (contentType === 'application/json') {
parsedData = JSON.parse(bodyStr);
} else {
const params = new URLSearchParams(bodyStr);

parsedData = Object.fromEntries(params);
}

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

return;
}

const dbPath = path.join(__dirname, '../db/expense.json');

fs.writeFile(dbPath, JSON.stringify(parsedData, null, 2), (error) => {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Using fs.writeFile here overwrites the file with every new expense. The requirement is to save all expenses. You'll need to first read the contents of db/expense.json, parse it into an array, add the new expense to that array, and then write the entire updated array back to the file.

if (error) {
response.statusCode = 500;
response.end('Internal Server Error');

return;
}

const accept = request.headers.accept || '';

if (accept.includes('text/html')) {
response.statusCode = 200;
response.setHeader('Content-Type', 'text/html');

response.end(`
<pre>${JSON.stringify(parsedData, null, 2)}</pre>
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Great job wrapping the JSON in <pre> tags! However, the response should display all the expenses that are saved in the file, not just the one that was newly added. After you fix the file-saving logic, you should have the full array of expenses available to stringify and send here.

`);
} else {
response.statusCode = 200;
response.setHeader('Content-Type', 'application/json');
response.end(JSON.stringify(parsedData));
}
});
} catch (error) {
response.statusCode = 400;
response.end('Invalid data');
}
});
} else {
response.statusCode = 404;
response.end('Not Found');
}
});
}

module.exports = {
Expand Down
16 changes: 16 additions & 0 deletions src/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<!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 method="post" action="/add-expense">
<input type="text" name="title" placeholder="Title">
<input type="text" name="amount" placeholder="Amount">
<input type="text" name="date" placeholder="Date">
<button type="submit">Add Expense</button>
</form>
</body>
</html>
Loading