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
64 changes: 61 additions & 3 deletions src/createServer.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,61 @@
// Write code here
// Also, you can create additional files in the src folder
// and import (require) them here
const http = require('http');
const { convertToCase } = require('./convertToCase/convertToCase');

const supportedCases = ['SNAKE', 'KEBAB', 'CAMEL', 'PASCAL', 'UPPER'];

function createServer() {
const server = http.createServer((req, res) => {
const [path, query] = req.url.split('?');
const text = path.slice(1);
const params = new URLSearchParams(query);
const toCase = params.get('toCase');

const errors = [];

if (!text) {
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 && !supportedCases.includes(toCase)) {
errors.push({
message: `This case is not supported. Available cases: SNAKE, KEBAB, CAMEL, PASCAL, UPPER.`,
});
}

res.setHeader('Content-Type', 'application/json');

if (errors.length) {
res.statusCode = 400;
res.statusMessage = 'Bad request';
res.end(JSON.stringify({ errors }));

return;
}

const result = convertToCase(text, toCase);

res.statusCode = 200;
res.statusMessage = 'Ok';
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

According to the task description, the status text for a successful response should be OK (all uppercase).


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

return server;
}

module.exports = { createServer };