diff --git a/src/convertToCase/convertToCase.js b/src/convertToCase/convertToCase.js index 893f384fb..b6c2bc047 100644 --- a/src/convertToCase/convertToCase.js +++ b/src/convertToCase/convertToCase.js @@ -1,3 +1,4 @@ +/* eslint-diable prettier/prettier */ const { detectCase } = require('./detectCase'); const { toWords } = require('./toWords'); const { wordsToCase } = require('./wordsToCase'); diff --git a/src/convertToCase/detectCase.js b/src/convertToCase/detectCase.js index c1825c76d..3c6ed7978 100644 --- a/src/convertToCase/detectCase.js +++ b/src/convertToCase/detectCase.js @@ -1,3 +1,4 @@ +/* eslint-disable prettier/prettier */ /** * @typedef {'SNAKE' | 'KEBAB' | 'CAMEL' | 'PASCAL' | 'UPPER'} CaseName * diff --git a/src/createServer.js b/src/createServer.js index 89724c920..97bb69e77 100644 --- a/src/createServer.js +++ b/src/createServer.js @@ -1,3 +1,61 @@ -// Write code here -// Also, you can create additional files in the src folder -// and import (require) them here +/* eslint-disable max-len */ +/* eslint-disable prettier/prettier */ +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 }; diff --git a/src/main.js b/src/main.js index b8d22f596..685bf04cf 100644 --- a/src/main.js +++ b/src/main.js @@ -1,3 +1,4 @@ +/* eslint-disable prettier/prettier */ const { createServer } = require('./createServer'); createServer().listen(5700, () => {