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
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
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"}
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.2",
"axios": "^1.7.2",
"eslint": "^8.57.0",
"eslint-plugin-jest": "^28.6.0",
Expand Down
Binary file added public/favicon.ico
Binary file not shown.
30 changes: 30 additions & 0 deletions public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
<link rel="stylesheet" href="style.css" />
<title>Form Data</title>
</head>
<body>
<div class="container">
<h1 class="header">Expenses Tracker</h1>
<form class="form" action="/add-expense" method="post">
<div class="input-wrapper">
<label for="date">Date</label>
<input type="date" name="date" id="date" />
</div>
<div class="input-wrapper">
<label for="title">Title</label>
<input type="text" name="title" id="title" />
</div>
<div class="input-wrapper">
<label for="amount">Amount</label>
<input type="number" name="amount" id="amount" />
</div>
<button type="submit" class="button-send">Send!</button>
</form>
</div>
</body>
</html>
67 changes: 67 additions & 0 deletions public/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
body {
padding: 0;
margin: 0;
}

.form {
display: flex;
gap: 1em;

align-items: flex-end;
}

.header {
display: flex;
padding: 0.5em;

border: 2px dashed black;
border-radius: 16px;

max-width: fit-content;
}

.container {
padding-top: 6em;
padding-left: 5em;

box-sizing: border-box;
display: flex;
flex-direction: column;
gap: 3em;
width: 100vw;
height: 100vh;
background-color: lemonchiffon;

color: black;
font-family: Arial, Helvetica, sans-serif;
font-weight: 500;
font-size: 18px;
line-height: 140%;
}

.input-wrapper {
display: flex;
flex-direction: column;
gap: 0.5em;
}

.button-send {
display: flex;
justify-content: center;
align-items: center;
padding: 8px;

max-height: fit-content;

background-color: green;
border: none;
color: white;
border-radius: 10px;

transition: all 0.2s ease;
}

.button-send:hover {
cursor: pointer;
background-color: lightgreen;
}
115 changes: 113 additions & 2 deletions src/createServer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,119 @@
'use strict';

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

const BASE_PUBLIC_DIR = path.resolve('public');

function sendBadRequest(res) {
res.statusCode = 400;
res.end('Bad request');
}

function sendStaticFiles(rawUrl, res) {
const normalizedUrl = rawUrl.slice(1) || 'index.html';
const filePath = path.resolve(BASE_PUBLIC_DIR, normalizedUrl);

if (!fs.existsSync(filePath)) {
res.statusCode = 404;
res.end('File not found!');

return;
}

const fileStream = fs.createReadStream(filePath);

fileStream.pipe(res);

fileStream.on('error', () => {
res.statusCode = 500;
res.end('Error during reading file');
});

fileStream.on('close', () => {
fileStream.destroy();
});
}

function handleRawFormData(formdata, res) {
if (!formdata) {
sendBadRequest(res);

return;
}

const dataToParams = new URLSearchParams(formdata);

if (
!dataToParams.get('date') ||
!dataToParams.get('title') ||
!dataToParams.get('amount')
) {
sendBadRequest(res);

return;
}

return Object.fromEntries(dataToParams);
}

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

server.on('request', (req, res) => {
res.statusCode = 200;

if (req.method === 'GET') {
sendStaticFiles(req.url, res);

return;
}

if (req.method === 'POST' && req.url === '/add-expense') {
res.setHeader('Content-type', 'application/json');

Choose a reason for hiding this comment

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

According to the task requirements, the server should respond with an HTML page. Therefore, the Content-Type header for this response should be set to text/html.


const chunks = [];
let rawData = '';

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

req.on('end', () => {
rawData = Buffer.concat(chunks).toString();

let preparedData = '';

// extra logic: in tests cases requests are in application/json,
// but IRL, formdata usually comes as application/x-form-encoded
// hope that MA guys will re-write this task (as well as previous one)
const contentTypeHeaders = req.headers['content-type'] || '';

if (contentTypeHeaders.includes('application/json')) {
preparedData = JSON.parse(rawData);
} else {
preparedData = handleRawFormData(rawData, res);
}

if (!preparedData.date || !preparedData.title || !preparedData.amount) {
sendBadRequest(res);

return;
}

fs.writeFile(
path.resolve('db/expense.json'),
JSON.stringify(preparedData),
() => {
res.end(JSON.stringify(preparedData));

Choose a reason for hiding this comment

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

The task requires returning an HTML page that displays the saved data, but the current implementation sends a raw JSON string. The JSON data should be embedded within an HTML structure, for example: <html><body><pre>${JSON.stringify(preparedData, null, 2)}</pre></body></html>.

},
Comment on lines +108 to +110

Choose a reason for hiding this comment

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

The callback for fs.writeFile receives an error object as its first argument. It's crucial to handle this case. If an error occurs during file writing, the server should send back an appropriate error response (e.g., status code 500).

);
});
}
});

return server;
}

module.exports = {
Expand Down