|
1 | | -// Write code here |
2 | | -// Also, you can create additional files in the src folder |
3 | | -// and import (require) them here |
| 1 | +const http = require('node:http'); |
| 2 | + |
| 3 | +const { convertToCase } = require('./convertToCase'); |
| 4 | + |
| 5 | +const SUPPORTED_CASES = ['SNAKE', 'KEBAB', 'CAMEL', 'PASCAL', 'UPPER']; |
| 6 | +const REQUEST_EXAMPLE = '"/<TEXT_TO_CONVERT>?toCase=<CASE_NAME>".'; |
| 7 | + |
| 8 | +const ERROR_MESSAGES = { |
| 9 | + missingText: [ |
| 10 | + 'Text to convert is required.', |
| 11 | + `Correct request is: ${REQUEST_EXAMPLE}`, |
| 12 | + ].join(' '), |
| 13 | + missingCase: [ |
| 14 | + '"toCase" query param is required.', |
| 15 | + `Correct request is: ${REQUEST_EXAMPLE}`, |
| 16 | + ].join(' '), |
| 17 | + unsupportedCase: [ |
| 18 | + 'This case is not supported.', |
| 19 | + 'Available cases: SNAKE, KEBAB, CAMEL, PASCAL, UPPER.', |
| 20 | + ].join(' '), |
| 21 | +}; |
| 22 | + |
| 23 | +function sendJson(res, statusCode, statusMessage, payload) { |
| 24 | + res.statusCode = statusCode; |
| 25 | + res.statusMessage = statusMessage; |
| 26 | + res.setHeader('Content-Type', 'application/json'); |
| 27 | + res.end(JSON.stringify(payload)); |
| 28 | +} |
| 29 | + |
| 30 | +function getRequestData(url) { |
| 31 | + const [path = '', queryString = ''] = url.split('?'); |
| 32 | + const text = path.startsWith('/') ? path.slice(1) : path; |
| 33 | + const params = new URLSearchParams(queryString); |
| 34 | + const toCase = params.get('toCase'); |
| 35 | + |
| 36 | + return { |
| 37 | + text, |
| 38 | + toCase, |
| 39 | + }; |
| 40 | +} |
| 41 | + |
| 42 | +function validateRequest(text, toCase) { |
| 43 | + const errors = []; |
| 44 | + |
| 45 | + if (!text) { |
| 46 | + errors.push({ message: ERROR_MESSAGES.missingText }); |
| 47 | + } |
| 48 | + |
| 49 | + if (!toCase) { |
| 50 | + errors.push({ message: ERROR_MESSAGES.missingCase }); |
| 51 | + } else if (!SUPPORTED_CASES.includes(toCase)) { |
| 52 | + errors.push({ message: ERROR_MESSAGES.unsupportedCase }); |
| 53 | + } |
| 54 | + |
| 55 | + return errors; |
| 56 | +} |
| 57 | + |
| 58 | +function createServer() { |
| 59 | + return http.createServer((req, res) => { |
| 60 | + const { text, toCase } = getRequestData(req.url || '/'); |
| 61 | + const errors = validateRequest(text, toCase); |
| 62 | + |
| 63 | + if (errors.length > 0) { |
| 64 | + sendJson(res, 400, 'Bad request', { errors }); |
| 65 | + |
| 66 | + return; |
| 67 | + } |
| 68 | + |
| 69 | + const { originalCase, convertedText } = convertToCase(text, toCase); |
| 70 | + |
| 71 | + sendJson(res, 200, 'OK', { |
| 72 | + originalCase, |
| 73 | + targetCase: toCase, |
| 74 | + originalText: text, |
| 75 | + convertedText, |
| 76 | + }); |
| 77 | + }); |
| 78 | +} |
| 79 | + |
| 80 | +module.exports = { |
| 81 | + createServer, |
| 82 | +}; |
0 commit comments