From 6048be040f290385f3351fde2aad70e9a0c6648f Mon Sep 17 00:00:00 2001 From: Medvid Oleksandr Date: Sat, 28 Dec 2024 18:16:56 +0200 Subject: [PATCH] server --- src/convertToCase/convertToCase.js | 1 + src/convertToCase/index.js | 1 + src/createServer.js | 64 ++++++++++++++++++++++++++++-- 3 files changed, 63 insertions(+), 3 deletions(-) diff --git a/src/convertToCase/convertToCase.js b/src/convertToCase/convertToCase.js index 893f384f..818b0580 100644 --- a/src/convertToCase/convertToCase.js +++ b/src/convertToCase/convertToCase.js @@ -5,6 +5,7 @@ const { wordsToCase } = require('./wordsToCase'); /** * @typedef {'SNAKE' | 'KEBAB' | 'CAMEL' | 'PASCAL' | 'UPPER'} CaseName * + // eslint-disable-next-line prettier/prettier * @param {string} text * @param {CaseName} caseName * diff --git a/src/convertToCase/index.js b/src/convertToCase/index.js index 0ac789ba..ba3d6371 100644 --- a/src/convertToCase/index.js +++ b/src/convertToCase/index.js @@ -1,3 +1,4 @@ +// eslint-disable-next-line prettier/prettier const { convertToCase } = require('./convertToCase'); module.exports = { diff --git a/src/createServer.js b/src/createServer.js index 89724c92..a12fbffc 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 +const http = require('http'); +const { convertToCase } = require('./convertToCase'); + +const createServer = () => { + return http.createServer((req, res) => { + const url = new URL(req.url, `http://${req.headers.host}`); + const toCase = url.searchParams.get('toCase'); + const PATH = url.pathname.slice(1); + const errors = []; + + if (!toCase) { + errors.push({ + message: + `"toCase" query param is required. ` + + `Correct request is: "/` + + `?toCase=".`, + }); + } else { + const supportedCases = ['SNAKE', 'KEBAB', 'CAMEL', 'PASCAL', 'UPPER']; + + if (!supportedCases.includes(toCase.toUpperCase())) { + errors.push({ + message: + 'This case is not supported. Available cases: ' + + 'SNAKE, KEBAB, CAMEL, PASCAL, UPPER.', + }); + } + } + + if (!PATH) { + errors.push({ + message: + 'Text to convert is required. Correct request is: ' + + '"/?toCase=".', + }); + } + + if (errors.length > 0) { + res.writeHead(400, { 'Content-Type': 'application/json' }); + res.write(JSON.stringify({ errors })); + + return res.end(); + } + + const text = convertToCase(PATH, toCase.toUpperCase()); + + const objectToReturn = { + originalText: PATH, + targetCase: toCase, + originalCase: text.originalCase, + convertedText: text.convertedText, + }; + + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify(objectToReturn)); + }); +}; + +module.exports = { + createServer, +};