diff --git a/src/createServer.js b/src/createServer.js index 89724c920..456df195d 100644 --- a/src/createServer.js +++ b/src/createServer.js @@ -1,3 +1,72 @@ -// Write code here -// Also, you can create additional files in the src folder -// and import (require) them here +/* eslint-disable max-len */ +const http = require('http'); +const { convertToCase } = require('./convertToCase'); + +const AVAILABLE_CASES = ['SNAKE', 'KEBAB', 'CAMEL', 'PASCAL', 'UPPER']; + +function createServer() { + const server = http.createServer((req, res) => { + res.setHeader('Content-Type', 'application/json'); + + const url = new URL(req.url, 'http://localhost'); + + const textToConvert = decodeURIComponent(url.pathname.slice(1)); + const toCase = url.searchParams.get('toCase'); + + const errors = []; + + if (!textToConvert) { + 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 && !AVAILABLE_CASES.includes(toCase)) { + errors.push({ + message: + 'This case is not supported. Available cases: SNAKE, KEBAB, CAMEL, PASCAL, UPPER.', + }); + } + + if (errors.length > 0) { + res.statusCode = 400; + res.statusMessage = 'Bad request'; + + res.end( + JSON.stringify({ + errors, + }), + ); + + return; + } + + const result = convertToCase(textToConvert, toCase); + + res.statusCode = 200; + res.statusMessage = 'OK'; + + res.end( + JSON.stringify({ + originalCase: result.originalCase, + targetCase: toCase, + originalText: textToConvert, + convertedText: result.convertedText, + }), + ); + }); + + return server; +} + +module.exports = { + createServer, +};