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
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
35 changes: 35 additions & 0 deletions src/createServer.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,44 @@
/* eslint-disable no-console */
'use strict';

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

function createServer() {
/* Write your code here */
// Return instance of http.Server class
return http.createServer((req, res) => {
const parts = req.url
.split('?')[0]
.replaceAll('//', '/')
.replaceAll('/', ',')
.split(',');
Comment on lines +10 to +14
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 multi-step string manipulation works, but there's a more standard and readable way to parse URL path parts. You could split the path by / and then filter out the resulting empty strings.

Since you're already creating a URL object on line 16, you can get the pathname from it and process it like this:

const myURL = new URL(req.url, 'http://localhost');
const parts = myURL.pathname.split('/').filter(p => p);

This would make the logic for getting parts much simpler.


const myURL = new URL(req.url, 'http://localhost');
const newSearchParams = new URLSearchParams(myURL.searchParams);

const responce = {};
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

You have a small typo here and in a few other places (responce). The correct spelling is response.


responce['parts'] = [];

if (parts.length > 0) {
for (const item of parts) {
if (item !== '') {
responce['parts'].push(item);
}
}
}

responce['query'] = {};

if (newSearchParams.size > 0) {
for (const [name, value] of newSearchParams) {
responce['query'][name] = value;
}
}
Comment on lines +33 to +37
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 loop works perfectly fine. For future reference, there's a more concise way to achieve the same result using Object.fromEntries():

responce['query'] = Object.fromEntries(newSearchParams);


res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(responce));
});
}

module.exports = {
Expand Down
Loading