Browse Source

Refactor nick implementation to use a global userlist

refactor/server
Sheogorath 6 years ago
parent
commit
1662775da7
No known key found for this signature in database GPG Key ID: 1F05CC3635CDDFFD
  1. 33
      src/server.js
  2. 12
      src/user.js
  3. 3
      src/userlist.js

33
src/server.js

@ -1,4 +1,5 @@
const net = require("net")
const User = require("../src/user.js")
const RPL_WELCOME = '001'
const ERR_NOSUCHNICK = '401'
@ -9,23 +10,12 @@ const ERR_ERRONEUSNICKNAME = '432'
const ERR_NICKNAMEINUSE = '433'
const ERR_NEEDMOREPARAMS = '461'
let server = {}
let userlist = {
0:
{
"nick": "chris",
1: "some value"
},
1:
{
"nick": "wayne",
1: "some_other_value"
}
}
let registeredUserlist = require("../src/userlist.js")
server.create = function create() {
return net.createServer((socket) => {
const user = new User(socket)
socket.on('data', function (data) {
let tokenized = data.toString("ascii").split("\r\n")[0].split(" ")
let command = tokenized[0].toUpperCase()
@ -38,19 +28,10 @@ server.create = function create() {
case "NICK":
if (tokenized[1]) {
let nickname = tokenized[1]
let nickNameCollision = 0
for (let clientID in userlist) {
console.log(clientID)
if (userlist[clientID]["nick"] === nickname) {
nickNameCollision = 1
delete userlist[clientID]
}
}
if (!nickNameCollision) {
let index = Object.keys(userlist).length
userlist[index] = {
"nick": nickname
}
// nick collision test
if (!Object.keys(registeredUserlist).includes(nickname)) {
user.setNickname(nickname)
registeredUserlist[nickname] = user
socket.write(RPL_WELCOME, " nick " + nickname + " succesfully added.")
} else {
socket.write(ERR_NICKNAMEINUSE, " nickname in use")

12
src/user.js

@ -0,0 +1,12 @@
const userlist = require("../src/userlist.js")
function User(socket) {
this.nickname = ""
this.connection = socket
this.setNickname = function(nickname) {
this.nickname = nickname
}
}
module.exports = User

3
src/userlist.js

@ -0,0 +1,3 @@
let userlist = {}
module.exports = userlist
Loading…
Cancel
Save