Skip to content
Open
Show file tree
Hide file tree
Changes from 2 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
7 changes: 4 additions & 3 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
module.exports = {
root: true,
extends: '@mate-academy/eslint-config',
env: {
jest: true
jest: true,
},
plugins: ['jest'],
rules: {
'no-proto': 0
'no-proto': 0,
},
plugins: ['jest']
};
23 changes: 23 additions & 0 deletions .github/workflows/test.yml-template
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: Test

on:
pull_request:
branches: [ master ]

jobs:
build:

runs-on: ubuntu-latest

strategy:
matrix:
node-version: [20.x]

steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- run: npm install
- run: npm test
9 changes: 5 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"license": "GPL-3.0",
"devDependencies": {
"@mate-academy/eslint-config": "latest",
"@mate-academy/scripts": "^1.8.6",
"@mate-academy/scripts": "^2.1.1",
"axios": "^1.7.2",
"eslint": "^8.57.0",
"eslint-plugin-jest": "^28.6.0",
Expand Down
55 changes: 53 additions & 2 deletions src/createServer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,59 @@
'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((req, res) => {
if (req.method === 'GET' && req.url === '/') {
fs.readFile(path.join(__dirname, 'form.html'), 'utf8', (err, content) => {
if (err) {
res.writeHead(500);
res.end('Error loading form');

return;
}
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(content);
});
} else if (req.method === 'POST' && req.url === '/add-expense') {
let data = '';

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

req.on('end', () => {
try {
const expense = JSON.parse(data);

if (!expense.date || !expense.title || !expense.amount) {
res.writeHead(400, { 'Content-Type': 'application/json' });

res.end(
'"Missing required fields: date, title, amount are required"',
);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Issue: The error response for missing fields is not a valid JSON object. It should be something like '{ "error": "Missing required fields: date, title, amount are required" }' to ensure clients can parse it as JSON.

Comment on lines +34 to +39
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Issue: The error response here is not a valid JSON object. You should send a JSON object like { "error": "Missing required fields: date, title, amount are required" } instead of a plain string. This is required for proper client-side error handling.


return;
}

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

fs.writeFileSync(filePath, JSON.stringify(expense, 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.

Critical Issue: This line overwrites the entire expense.json file with only the latest expense. According to the requirements, you must append each new expense to an array in the file. Please update your logic to read the existing array, add the new expense, and write the updated array back to the file.


res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(expense));
} catch (err) {
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end('"Failed to process request"');
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Issue: The error response for a failed request is not a valid JSON object. It should be '{ "error": "Failed to process request" }' for proper JSON parsing by clients.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Issue: The error response here is not a valid JSON object. You should send a JSON object like { "error": "Failed to process request" } instead of a plain string.

}
});
} else {
res.writeHead(404);
res.end();
}
});
}

module.exports = {
Expand Down
95 changes: 95 additions & 0 deletions src/form.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Expense Form</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 0 auto;
padding: 20px;
}
form {
background: #f9f9f9;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
input {
width: 100%;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
box-sizing: border-box;
}
button {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<form id="expenseForm">
<div class="form-group">
<label for="date">Date:</label>
<input type="date" id="date" name="date" required>
</div>
<div class="form-group">
<label for="title">Title:</label>
<input type="text" id="title" name="title" required>
</div>
<div class="form-group">
<label for="amount">Amount:</label>
<input type="text" id="amount" name="amount" required>
</div>
<button type="submit">Save Expense</button>
</form>

<script>
document.getElementById('expenseForm').addEventListener('submit', async (e) => {
e.preventDefault();

const formData = {
date: document.getElementById('date').value,
title: document.getElementById('title').value,
amount: document.getElementById('amount').value
};

try {
const response = await fetch('/add-expense', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
});

const result = await response.json();
if (response.ok) {
alert('Expense saved successfully!');
} else {
alert(`Error: ${result}`);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Minor issue: The error alert displays the entire 'result' object, which may not be user-friendly. Consider displaying a specific error message, such as 'result.error', if available, for clearer feedback to the user.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Issue: The error alert displays the entire result object, which may not be user-friendly. You should display a specific error message, such as result.error, to provide clearer feedback to the user.

}
} catch (err) {
alert('Error saving expense');
}
});
</script>
</body>
</html>