Skip to content
Open
Show file tree
Hide file tree
Changes from 2 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
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
111 changes: 109 additions & 2 deletions src/createServer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,115 @@
'use strict';

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

const dataPath = path.resolve(__dirname, '../db/expense.json');

function readBody(req) {
return new Promise((resolve) => {
let body = '';

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

req.on('end', () => resolve(body));
});
}

function parseBody(rawBody, contentType = '') {
if (!rawBody) {
return null;
}

if (contentType.includes('application/json')) {
try {
return JSON.parse(rawBody);
} catch {
return null;
}
}

if (contentType.includes('application/x-www-form-urlencoded')) {
const params = new URLSearchParams(rawBody);
const obj = {};

for (const [key, value] of params.entries()) {
obj[key] = value;
}

return obj;
}

return null;
}

function isValidExpense(expense) {
return (
expense &&
typeof expense.date === 'string' &&
typeof expense.title === 'string' &&
typeof expense.amount === 'string' &&
expense.date &&
expense.title &&
expense.amount
);
}

function createServer() {
/* Write your code here */
// Return instance of http.Server class
return http.createServer(async (req, res) => {
const { method, url } = req;

if (method === 'GET' && url === '/') {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');

res.end(`<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Add expense</title>
</head>
<body>
<h1>Add expense</h1>
<form method="POST" action="/add-expense">
<label>Date <input type="date" name="date" required></label><br>
<label>Title <input type="text" name="title" required></label><br>
<label>Amount <input type="text" name="amount" required></label><br>
<button type="submit">Save</button>
</form>
</body>
</html>`);

return;
}

if (method === 'POST' && url === '/add-expense') {
const rawBody = await readBody(req);
const parsed = parseBody(rawBody, req.headers['content-type'] || '');

if (!isValidExpense(parsed)) {
res.statusCode = 400;
res.setHeader('Content-Type', 'text/plain');
res.end('Invalid expense data');

return;
}

fs.writeFileSync(dataPath, JSON.stringify(parsed, null, 2));
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This line overwrites the expense.json file with only the latest submission. To save all expenses, you should first read the existing data from the file, add the new expense to the collection (likely an array), and then write the entire collection back to the file.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This line overwrites expense.json with only the new expense, but the requirement is to add to it. You need to first read the file's content, parse it as an array, push the new parsed expense into that array, and then write the entire updated array back to the file. Remember to handle cases where the file might not exist or is empty.


res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(parsed));
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The requirement is to 'return an HTML page with well formatted JSON'. Currently, you are returning a response with Content-Type: application/json, which is just the raw JSON data. Consider wrapping the JSON output in a basic HTML structure (e.g., using <pre> tags) and setting the Content-Type header to text/html.

Copy link
Copy Markdown

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 after submission, not raw JSON. The Content-Type header should be text/html. The response body should be an HTML document that includes the submitted JSON, preferably inside a <pre> tag for proper formatting.


return;
}

res.statusCode = 404;
res.setHeader('Content-Type', 'text/plain');
res.end('Not found');
});
}

module.exports = {
Expand Down