Skip to content
Open
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
65 changes: 62 additions & 3 deletions src/createServer.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,62 @@
// Write code here
// Also, you can create additional files in the src folder
// and import (require) them here
/* eslint-disable max-len */

const http = require('http');
const { convertToCase } = require('./convertToCase');

const createServer = () => {
const server = http.createServer((req, res) => {
const url = new URL(req.url, `http://${req.headers.host}`);
const textToConvert = url.pathname.slice(1);
const toCase = url.searchParams.get('toCase');

const errors = [];

if (!textToConvert) {
errors.push({
message:
'Text to convert is required. Correct request is: "/<TEXT_TO_CONVERT>?toCase=<CASE_NAME>".',
});
}

if (!toCase) {
errors.push({
message:
'"toCase" query param is required. Correct request is: "/<TEXT_TO_CONVERT>?toCase=<CASE_NAME>".',
});
}

if (
toCase &&
!['SNAKE', 'KEBAB', 'CAMEL', 'PASCAL', 'UPPER'].includes(toCase)
) {
errors.push({
message:
'This case is not supported. Available cases: SNAKE, KEBAB, CAMEL, PASCAL, UPPER.',
});
}

if (errors.length > 0) {
res.writeHead(400, 'Bad request', { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ errors }));

return;
}

const result = convertToCase(textToConvert, toCase);

res.writeHead(200, 'OK', { 'Content-Type': 'application/json' });

res.end(
JSON.stringify({
originalCase: result.originalCase,
targetCase: toCase,
originalText: textToConvert,
convertedText: result.convertedText,
}),
);
});

return server;
};

module.exports = { createServer };