diff --git a/src/convertToCase/detectCase.js b/src/convertToCase/detectCase.js index c1825c76d..c024c5a12 100644 --- a/src/convertToCase/detectCase.js +++ b/src/convertToCase/detectCase.js @@ -10,7 +10,6 @@ function detectCase(text) { } if (text.toLowerCase() === text) { - if (text.includes('_') || text.includes('-')) { // There are no uppercase in the text, so it's one of the lower cases // See if they're snake or kebab if (text.includes('_')) { @@ -21,7 +20,6 @@ function detectCase(text) { return 'KEBAB'; } } - } if (text[0].toUpperCase() === text[0]) { return 'PASCAL'; diff --git a/src/createServer.js b/src/createServer.js index 89724c920..b80c8e3ab 100644 --- a/src/createServer.js +++ b/src/createServer.js @@ -1,3 +1,58 @@ -// 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 CASES = ['SNAKE', 'KEBAB', 'CAMEL', 'PASCAL', 'UPPER']; + +function validateParams(text, toCase) { + const errors = []; + + if (!text) { + errors.push({ + message: + 'Text to convert is required. Correct request is: "/?toCase=".', + }); + } + + if (!toCase) { + errors.push({ + message: + '"toCase" query param is required. Correct request is: "/?toCase=".' + }); + } + + if (toCase && !CASES.includes(toCase.toUpperCase())) { + errors.push({ + message: + 'This case is not supported. Available cases: SNAKE, KEBAB, CAMEL, PASCAL, UPPER.' + }); + } + + return errors; +} + +function createServer() { + return http.createServer(function (req, res) { + const [path, queryString] = req.url.split('?'); + + const params = new URLSearchParams(queryString); + const toCase = params.get('toCase'); + const errors = validateParams(path.slice(1), toCase); + + if (errors.length) { + res.setHeader('Content-Type', 'application/json'); + res.statusCode = 400; + res.end(JSON.stringify({ errors })); + + return; + } + + const target = { originalText: path.slice(1), targetCase: toCase }; + const result = convertToCase(path.slice(1), toCase); + + res.setHeader('Content-Type', 'application/json'); + res.statusCode = 200; + + res.end(JSON.stringify({ ...result, ...target })); + }); +} + +module.exports = { createServer };