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
6 changes: 1 addition & 5 deletions db/expense.json
Original file line number Diff line number Diff line change
@@ -1,5 +1 @@
{
"date": "2024-01-25",
"title": "Test Expense",
"amount": "100"
}
{"date":"2024-01-25","title":"Test Expense","amount":"100"}
35 changes: 19 additions & 16 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.3",
"axios": "^1.7.2",
"eslint": "^8.57.0",
"eslint-plugin-jest": "^28.6.0",
Expand Down
16 changes: 16 additions & 0 deletions public/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="date" name="date" />
<input type="text" name="title" placeholder="Title" />
<input type="number" name="amount" placeholder="Amount" />
<button type="submit">Add Expense</button>
</form>
</body>
</html>
105 changes: 105 additions & 0 deletions src/createServer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,113 @@
'use strict';

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

function createServer() {
/* Write your code here */
// Return instance of http.Server class
const server = http.Server();

return server.on('request', (req, res) => {
const url = new URL(req.url, `http://${req.headers.host}`);
const pathname = url.pathname.slice(1) || 'index.html';
const filePath = path.join('public', pathname);
const expensePath = path.join('db', 'expense.json');

if (req.method === 'POST' && pathname === 'add-expense') {
const chunks = [];

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

req.on('end', () => {
const body = Buffer.concat(chunks).toString();
const contentType = req.headers['content-type']
? req.headers['content-type'].split(';')[0].trim()
: '';

let result = null;

if (contentType === 'application/json') {
try {
result = JSON.parse(body);
} catch (err) {
res.statusCode = 400;
res.end('Bad Request');

return;
}
} else if (contentType === 'application/x-www-form-urlencoded') {
result = {};

body.split('&').forEach((pair) => {
const [key, value] = pair.split('=');

if (!key || value === undefined) {
result = null;

res.statusCode = 400;
res.end('Bad Request');

return;
}
result[key] = decodeURIComponent(value.replace(/\+/g, ' '));
});
} else {
try {
result = JSON.parse(body);
} catch (err) {
result = null;

res.statusCode = 400;
res.end('Bad Request');
}
}

const requiredFields = ['date', 'title', 'amount'];

if (
!result ||
typeof result !== 'object' ||
!requiredFields.every((key) => key in result)
) {
res.statusCode = 400;
res.end('Bad Request');

return;
}

if (!fs.existsSync(path.dirname(expensePath))) {
fs.mkdirSync(path.dirname(expensePath), { recursive: true });
}

fs.writeFileSync(expensePath, JSON.stringify(result));

res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end(`<html><pre>${JSON.stringify(result, null, 2)}</pre></html>`);
});
} else {
if (!fs.existsSync(filePath)) {
res.statusCode = 404;
res.end('File not found');

return;
}

const fileStream = fs.createReadStream(filePath);

fileStream.pipe(res).on('error', () => {
res.statusCode = 500;
res.end('Internal Server Error');
});

res.setHeader('Content-Type', 'text/html');
res.statusCode = 200;
}
});
}

module.exports = {
Expand Down
Loading