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: 3 additions & 3 deletions db/expense.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"date": "2024-01-25",
"title": "Test Expense",
"amount": "100"
"date": "2026-03-20",
"title": "dsff",
"amount": "5"
}
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.3",
"axios": "^1.7.2",
"eslint": "^8.57.0",
"eslint-plugin-jest": "^28.6.0",
Expand Down
78 changes: 78 additions & 0 deletions public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Expense Form</title>
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<form id="expenseForm">
<h1>Add Expense</h1>

<label for="date">Date:</label>
<input type="date" id="date" name="date" required>

<label for="title">Title:</label>
<input type="text" id="title" name="title" required>

<label for="amount">Amount:</label>
<input type="number" id="amount" name="amount" step="0.01" required>

<button type="submit">Submit Expense</button>
</form>

<div id="result"></div>

<script>
const form = document.getElementById('expenseForm');
const resultDiv = document.getElementById('result');

form.addEventListener('submit', async (e) => {
e.preventDefault();

const formData = {
date: document.getElementById('date').value,
title: document.getElementById('title').value,
amount: document.getElementById('amount').value,
};

try {
const response = await fetch('/add-expense', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
});

const data = await response.text();

if (response.ok) {
resultDiv.innerHTML = `
<div class="success">
<h2>Expense Saved Successfully!</h2>
${data}
</div>
`;
form.reset();
} else {
resultDiv.innerHTML = `
<div class="error">
<h2>Error</h2>
<p>${data}</p>
</div>
`;
}
} catch (error) {
resultDiv.innerHTML = `
<div class="error">
<h2>Error</h2>
<p>${error.message}</p>
</div>
`;
}
});
</script>
</body>
</html>
89 changes: 89 additions & 0 deletions public/styles.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 50px auto;
padding: 20px;
background-color: #f5f5f5;
}

form {
background: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
margin-bottom: 20px;
}

h1 {
color: #333;
margin-bottom: 30px;
}

label {
display: block;
margin-bottom: 5px;
color: #555;
font-weight: bold;
}

input {
width: 100%;
padding: 10px;
margin-bottom: 20px;
border: 1px solid #ddd;
border-radius: 4px;
box-sizing: border-box;
font-size: 14px;
}

button {
background-color: #4CAF50;
color: white;
padding: 12px 30px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
width: 100%;
}

button:hover {
background-color: #45a049;
}

#result {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
display: none;
}

#result:not(:empty) {
display: block;
}

.success {
color: #4CAF50;
}

.success h2 {
margin-top: 0;
}

.error {
color: #f44336;
}

.error h2 {
margin-top: 0;
}

pre {
background-color: #f5f5f5;
padding: 15px;
border-radius: 4px;
overflow-x: auto;
color: #333;
font-size: 14px;
}
127 changes: 125 additions & 2 deletions src/createServer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,131 @@
'use strict';

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

/**
* Helper function to send HTTP responses
* @param {http.ServerResponse} res - Response object
* @param {number} statusCode - HTTP status code (200, 404, 500, etc.)
* @param {string} contentType - Content-Type header value
* @param {string|object} data - Data to send (will be stringified if object)
*/
function sendResponse(res, statusCode, contentType, data) {
res.writeHead(statusCode, { 'Content-Type': contentType });

// If data is an object and content type is JSON, stringify it
if (typeof data === 'object' && contentType === 'application/json') {
res.end(JSON.stringify(data));
} else {
res.end(data);
}
}

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

// Serve index.html
if (method === 'GET' && url === '/') {
const filePath = path.resolve(__dirname, '../public/index.html');

fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
sendResponse(res, 500, 'text/plain', 'Error loading page');

return;
}

sendResponse(res, 200, 'text/html', data);
});

return;
}

// Serve styles.css
if (method === 'GET' && url === '/styles.css') {
const filePath = path.resolve(__dirname, '../public/styles.css');

fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
sendResponse(res, 500, 'text/plain', 'Error loading stylesheet');

return;
}

sendResponse(res, 200, 'text/css', data);
});

return;
}

// Handle POST request - save expense data
if (method === 'POST' && url === '/add-expense') {
let body = '';

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

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

try {
// Parse JSON body
expense = JSON.parse(body);
} catch (error) {
sendResponse(res, 400, 'application/json', { error: 'invalid JSON' });

return;
}

// Validate required fields
const requiredFields = ['date', 'title', 'amount'];
const missingFields = requiredFields.filter((field) => !expense[field]);

if (missingFields.length > 0) {
sendResponse(
res,
400,
'text/plain',
`Missing required fields: ${missingFields.join(', ')}`,
);

return;
}

// Save to file
const dataPath = path.resolve(__dirname, '../db/expense.json');
const dirPath = path.dirname(dataPath);

// Enshore directory exists
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
}

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

// Return HTML page with well-formatted JSON
const html = `<pre>${JSON.stringify(expense, null, 2)}</pre>`;

sendResponse(res, 200, 'text/html', html);
} catch (error) {
sendResponse(res, 500, 'application/json', {
error: 'Failed to save expense',
});
}
});

return;
}

// Handle 404 for all other routes
sendResponse(res, 404, 'text/plain', 'Not found');
});

return server;
}

module.exports = {
Expand Down
6 changes: 4 additions & 2 deletions tests/formDataServer.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,10 @@ describe('Form Data Server', () => {
};
const response = await axios.post(`${HOST}/add-expense`, expense);

expect(response.headers['content-type']).toBe('application/json');
expect(response.data).toStrictEqual(expense);
expect(response.headers['content-type']).toBe('text/html');
expect(response.data).toBe(
`<pre>${JSON.stringify(expense, null, 2)}</pre>`,
);
});

it('should return 404 for invalid url', async () => {
Expand Down