From 8de73b16960a9fb1cff083d316780f3bf741c26a Mon Sep 17 00:00:00 2001 From: Tymur Date: Mon, 25 May 2026 11:17:13 +0300 Subject: [PATCH] add task solution --- src/convertToCase/convertToCase.js | 2 +- src/createServer.js | 75 ++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 1 deletion(-) diff --git a/src/convertToCase/convertToCase.js b/src/convertToCase/convertToCase.js index 893f384fb..c224213b2 100644 --- a/src/convertToCase/convertToCase.js +++ b/src/convertToCase/convertToCase.js @@ -19,7 +19,7 @@ function convertToCase(text, caseName) { const words = toWords(text, originalCase); const convertedText = wordsToCase(words, caseName); - return { originalCase, convertedText }; + return { convertedText, originalCase }; } module.exports = { diff --git a/src/createServer.js b/src/createServer.js index 89724c920..bcceea079 100644 --- a/src/createServer.js +++ b/src/createServer.js @@ -1,3 +1,78 @@ +/* eslint-disable no-console */ // Write code here // Also, you can create additional files in the src folder // and import (require) them here +function createServer() { + const http = require('http'); + const { convertToCase } = require('./convertToCase/convertToCase'); + + // const PORT = process.env.PORT || 3000; + + const server = http.createServer((req, res) => { + const [textToConvert, query = ''] = req.url.slice(1).split('?'); + const toCase = new URLSearchParams(query).get('toCase'); + + res.setHeader('Content-Type', 'application/json'); + + const errors = []; + + if (textToConvert.length === 0) { + errors.push({ + message: + // eslint-disable-next-line max-len + 'Text to convert is required. Correct request is: "/?toCase=".', + }); + } + + if (toCase === null) { + errors.push({ + message: + // eslint-disable-next-line max-len + '"toCase" query param is required. Correct request is: "/?toCase=".', + }); + } + + if ( + toCase !== null && + toCase !== 'SNAKE' && + toCase !== 'KEBAB' && + toCase !== 'CAMEL' && + toCase !== 'PASCAL' && + toCase !== 'UPPER' + ) { + errors.push({ + message: + // eslint-disable-next-line max-len + 'This case is not supported. Available cases: SNAKE, KEBAB, CAMEL, PASCAL, UPPER.', + }); + } + + if (errors.length > 0) { + res.statusCode = 400; + + res.end( + JSON.stringify({ + errors: [...errors], + }), + ); + + return; + } + + res.statusCode = 200; + + res.end( + JSON.stringify({ + ...convertToCase(textToConvert, toCase), + originalText: textToConvert, + targetCase: toCase, + }), + ); + }); + + return server; +} + +module.exports = { + createServer, +};