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

const http = require('http');
const fs = require('fs').promises;

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

if (parsedUrl.pathname !== '/add-expense') {
res.statusCode = 404;

return res.end('Bad request');
}

let requestBody = '';

for await (const chunk of req) {
requestBody += chunk;
}

let expenseData;

try {
expenseData = JSON.parse(requestBody);
} catch (error) {
res.statusCode = 400;

return res.end(`${error.message} error`);
}

const { date, title, amount } = expenseData;

if (!date || !title || !amount) {
res.statusCode = 404;
Comment thread
oleksandr-kovalchuk marked this conversation as resolved.
Outdated

return res.end('No data received');
}

try {
await fs.writeFile('./db/expense.json', requestBody);
Comment thread
oleksandr-kovalchuk marked this conversation as resolved.
Outdated
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(requestBody);
} catch (error) {
res.statusCode = 500;
res.end('error saving data');
}
});

return server;
}

module.exports = {
Expand Down
17 changes: 17 additions & 0 deletions src/db/expense.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[
{
"id": "1741863024015",
"amount": null,
Comment thread
oleksandr-kovalchuk marked this conversation as resolved.
Outdated
"createdAt": "2025-03-13T10:50:24.015Z"
},
{
"id": "1741863024066",
"amount": null,
Comment thread
oleksandr-kovalchuk marked this conversation as resolved.
Outdated
"createdAt": "2025-03-13T10:50:24.066Z"
},
{
"id": "1741863024083",
"amount": null,
Comment thread
oleksandr-kovalchuk marked this conversation as resolved.
Outdated
"createdAt": "2025-03-13T10:50:24.083Z"
}
]