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
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
12 changes: 7 additions & 5 deletions db/expense.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
{
"date": "2024-01-25",
"title": "Test Expense",
"amount": "100"
}
[
{
"date": "2024-01-25",
"title": "Test Expense",
"amount": "100"
}
]
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
83 changes: 81 additions & 2 deletions src/createServer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,87 @@
'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(
JSON.stringify({
error:
'Missing required fields: date, title, amount are required',
}),
);

return;
}

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

// Initialize expenses array
let expenses = [];

// Read existing expenses if file exists
if (fs.existsSync(filePath)) {
try {
const fileContent = fs.readFileSync(filePath, 'utf8');
const parsedContent = JSON.parse(fileContent);

expenses = Array.isArray(parsedContent) ? parsedContent : [];
} catch (readError) {
// If file is corrupted, start with empty array
expenses = [];
}
}

// Add new expense
expenses.push(expense);

// Write updated array back to file
fs.writeFileSync(filePath, JSON.stringify(expenses, null, 2));

res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(expense));
} catch (err) {
res.writeHead(500, { 'Content-Type': 'application/json' });

res.end(
JSON.stringify({
error: 'Failed to process request',
}),
);
}
});
} 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.error || 'Unknown error occurred'}`);
}
} catch (err) {
alert('Error saving expense');
}
});
</script>
</body>
</html>
Loading