diff --git a/src/createServer.js b/src/createServer.js index 89724c920..d9f71bd39 100644 --- a/src/createServer.js +++ b/src/createServer.js @@ -1,3 +1,67 @@ -// 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'); + +function createServer() { + const server = http.createServer((req, res) => { + const url = req.url || ''; + const [path, queryString = ''] = url.split('?'); + + const text = path.slice(1); + const params = new URLSearchParams(queryString || ''); + const toCase = params.get('toCase'); + + const errors = []; + + const allowedCases = ['SNAKE', 'KEBAB', 'CAMEL', 'PASCAL', 'UPPER']; + + 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 && !allowedCases.includes(toCase)) { + errors.push({ + message: + 'This case is not supported. ' + + 'Available cases: SNAKE, KEBAB, CAMEL, PASCAL, UPPER.', + }); + } + + if (errors.length) { + res.statusCode = 400; + res.statusMessage = 'Bad request'; + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify({ errors })); + } else { + const result = convertToCase(text, toCase); + + res.statusCode = 200; + res.statusMessage = 'OK'; + res.setHeader('Content-Type', 'application/json'); + + res.end( + JSON.stringify({ + originalCase: result.originalCase, + targetCase: toCase, + originalText: text, + convertedText: result.convertedText, + }), + ); + } + }); + + return server; +} + +module.exports = { createServer };