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
91 changes: 89 additions & 2 deletions src/createServer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,95 @@
'use strict';

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

/**
* Creates an HTTP server that handles expense form submissions.
* @returns {http.Server} The configured HTTP server.
*/
function createServer() {
/* Write your code here */
// Return instance of http.Server class
const server = http.createServer((req, res) => {
// Обробляємо GET-запит на головну сторінку
if (req.method === 'GET' && req.url === '/') {
const indexPath = path.join(__dirname, 'index.html');

fs.readFile(indexPath, (err, data) => {
if (err) {
res.writeHead(404, 'Not Found', { 'Content-Type': 'text/plain' });
res.end('404 Not Found: index.html not found');

return;
}
res.writeHead(200, 'OK', { 'Content-Type': 'text/html' });
res.end(data);
});

return;
}

// Обробляємо POST-запит на /add-expense
if (req.method === 'POST' && req.url === '/add-expense') {
const form = new formidable.IncomingForm();

form.parse(req, (err, fields) => {
if (err) {
res.writeHead(400, 'Bad Request', { 'Content-Type': 'text/plain' });
res.end('400 Bad Request: Error parsing form');

return;
}

// Перевіряємо наявність усіх полів
const { date, title, amount } = fields;

if (!date || !title || !amount) {
res.writeHead(400, 'Bad Request', { 'Content-Type': 'text/plain' });

res.end(
'400 Bad Request: Missing required fields (date, title, or amount)',
);

return;
}

// Створюємо об'єкт витрати з amount як рядком
const expense = {
date: date.toString(),
title: title.toString(),
amount: amount.toString(), // Зберігаємо amount як рядок
};

// Шлях до файлу db/expense.json
const dbPath = path.join(__dirname, '..', 'db', 'expense.json');

// Зберігаємо одиночний об'єкт, перезаписуючи файл
try {
fs.writeFileSync(dbPath, JSON.stringify(expense, null, 2));
} catch (error) {
res.writeHead(500, 'Internal Server Error', {
'Content-Type': 'text/plain',
});
res.end('500 Internal Server Error: Error writing to expense.json');

return;
}

// Повертаємо JSON-відповідь
res.writeHead(200, 'OK', { 'Content-Type': 'application/json' });
res.end(JSON.stringify(expense)); // Повертаємо додану витрату
});

return;
}

// Обробляємо неіснуючі маршрути (404)
res.writeHead(404, 'Not Found', { 'Content-Type': 'text/plain' });
res.end('404 Not Found');
});

return server;
}

module.exports = {
Expand Down
28 changes: 28 additions & 0 deletions src/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Expense Tracker</title>
</head>
<body>
<h1>Add an Expense</h1>
<form action="/add-expense" method="POST" enctype="multipart/form-data">
<div>
<label for="date">Date:</label>
<input type="date" id="date" name="date" required>
</div>
<div>
<label for="title">Title:</label>
<input type="text" id="title" name="title" required>
</div>
<div>
<label for="amount">Amount:</label>
<input type="number" id="amount" name="amount" step="0.01" required>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
</body>
</html>
Loading