From 9e749d7aa3b651b3a52ff9c885dcb369ddbc498a Mon Sep 17 00:00:00 2001 From: adb-sh Date: Wed, 29 Jul 2020 01:05:08 +0200 Subject: [PATCH] backend is coming --- index.js | 36 +++++++++++++++++++++++++++++++++++- public/index.html | 17 ++++++++++------- 2 files changed, 45 insertions(+), 8 deletions(-) diff --git a/index.js b/index.js index 79e3db6..703150e 100644 --- a/index.js +++ b/index.js @@ -2,7 +2,15 @@ const http = require('http'); const url = require('url'); const fs = require('fs'); const ws = require('ws'); +const redis = require('redis') +//redis client +const redis_client = redis.createClient() +redis_client.on("error", function (error) { + console.error(error) +}) + +//HTTP server http.createServer(function (req, res) { const q = url.parse(req.url, true); let filename = "./public" + q.pathname; @@ -18,6 +26,7 @@ http.createServer(function (req, res) { }); }).listen(8080); +//WS server const wss = new ws.Server({ port: 8081, perMessageDeflate: { @@ -41,10 +50,35 @@ const wss = new ws.Server({ } }); +//WS handler wss.on('connection', ws => { ws.on('message', message => { console.log(`Received message => ${message}`) - if ({message} == 'long_url ') ws.send('error: url is empty') + let msg = `${message}`.split(";", 2) + if (msg[0] === 'long_url') { + if (msg[1] === '') ws.send('error;url is empty') + if (msg[1].length > 2000) ws.send('error;your url is too big') + else{ + let ran_key = get_key(8) + //redis_client.set("key", "value", redis.print) + ws.send('short_url;http://127.0.0.1'+ran_key) + } + } + //ws.send('got your request: '+msg) + console.log(msg[0]) }) ws.send('websocket connected') }) + +//random key +const forbidden_array = ['sym', 'admin', 'stats'] +function get_key(length) { + let forbidden = false; let output = '' + let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' + do{ + for (let i = 0; i < length; i++ ) + output += characters.charAt(Math.floor(Math.random() * characters.length)) + for (let i = 0; i < forbidden_array.length; i++) if (output === forbidden_array[i]) forbidden = true + } while (forbidden) + return output +} diff --git a/public/index.html b/public/index.html index f53bc7a..fa087a7 100644 --- a/public/index.html +++ b/public/index.html @@ -5,19 +5,22 @@