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
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
114 changes: 112 additions & 2 deletions src/createServer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,118 @@
'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 === 'object' &&
typeof expense.date === 'string' &&
typeof expense.title === 'string' &&
typeof expense.amount === 'string' &&
expense.date.trim() &&
expense.title.trim() &&
expense.amount.trim()
);
}

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" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<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 contentType = String(req.headers['content-type'] || '');
const expense = parseBody(rawBody, contentType);

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

return;
}

fs.writeFileSync(dataPath, JSON.stringify(expense, null, 2));

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 new expense. The requirement is to add the new expense to the existing ones.

You'll need to first read the file's content (e.g., with fs.readFileSync), parse the JSON into an array, push the new expense into that array, and then write the updated array back to the file.


res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(expense));
Comment on lines +106 to +107

Choose a reason for hiding this comment

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

The response here is raw JSON. According to the task description, you need to respond with an HTML page.

The Content-Type header should be text/html, and the body should be an HTML document that displays the submitted JSON, for example, inside a <pre> tag for nice formatting.


return;
}

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

module.exports = {
Expand Down