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
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
31 changes: 31 additions & 0 deletions public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Form Data</title>
</head>

<body>
<h1>Form Data</h1>
<form
action="/add-expense"
method="post"
enctype="application/x-www-form-urlencoded"
>
<label for="date">Date:</label>
<input id="date" name="date" type="date" />
<br />
<br />
<label for="title">Title:</label>
<input id="title" name="title" type="text" />
<br />
<br />
<label for="amount">Amount:</label>
<input id="amount" name="amount" type="number" />
<br />
<br />
<button type="submit">Send</button>
</form>
</body>
</html>
109 changes: 107 additions & 2 deletions src/createServer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,113 @@
'use strict';

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

function createServer() {
/* Write your code here */
// Return instance of http.Server class
const server = http.createServer((req, res) => {
const reqUrl = new URL(req.url || '', `http://${req.headers.host}`);
const pathname = reqUrl.pathname;

if (req.method === 'GET' && pathname === '/') {
const indexPath = path.resolve('public', 'index.html');

res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
fs.createReadStream(indexPath).pipe(res);

return;
}

if (req.method === 'GET' && pathname === '/add-expense') {
res.statusCode = 400;

return res.end('Only POST method allowed');
}

if (req.method === 'POST' && pathname === '/add-expense') {
let body = '';

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

req.on('end', () => {
let dataObj;

try {
const contentType = req.headers['content-type'];

if (contentType.includes('application/json')) {
dataObj = JSON.parse(body);
} else if (
contentType.includes('application/x-www-form-urlencoded')
) {
const parsed = new URLSearchParams(body);

dataObj = Object.fromEntries(parsed.entries());
} else {
res.writeHead(400, { 'Content-Type': 'text/plain' });

return res.end('Unsupported content type');
}

const { date, title, amount } = dataObj;

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

return res.end('Invalid data format');
}

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

fs.readFile(filePath, (err, fileData) => {
let parsedFileData = [];

if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });

return res.end(`Server error: ${err}`);
} else {
parsedFileData = JSON.parse(fileData);

if (typeof parsedFileData === 'object') {
if (Object.keys(parsedFileData).length) {
parsedFileData = [parsedFileData];
parsedFileData.push(dataObj);
} else if (!Object.keys(parsedFileData).length) {
parsedFileData = dataObj;
} else if (Array.isArray(parsedFileData)) {
parsedFileData.push(dataObj);
}
}
Comment on lines +75 to +84
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 logic for updating 'parsedFileData' is incorrect. If 'parsedFileData' is already an array, the code will not reach the 'Array.isArray(parsedFileData)' branch due to the previous 'if (typeof parsedFileData === 'object')' and its nested conditions. This can lead to incorrect data structure and loss of previous expenses. You should first check if 'parsedFileData' is an array, and if so, push the new expense. If it's an object (and not an array), convert it to an array with the existing object and the new one. If it's empty, initialize it as an array with the new expense. Please revise this logic to ensure expenses are always stored as an array and new entries are appended correctly.


const newData = JSON.stringify(parsedFileData, null, 2);

fs.writeFile(filePath, newData, (error) => {
if (error) {
res.writeHead(500, { 'Content-Type': 'text/plain' });

return res.end(`Server error: ${error}`);
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(newData);
});
}
});
} catch (e) {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end(`Invalid request body: ${e.message}`);
}
});
} else {
res.statusCode = 404;
res.end('Not found');
}
});

return server;
}

module.exports = {
Expand Down