Skip to content

Commit

Permalink
Switch sockets to mixin instead of own class
Browse files Browse the repository at this point in the history
  • Loading branch information
travis-w committed Dec 26, 2017
1 parent 9b5f8d2 commit 15b3ac0
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 16 deletions.
9 changes: 4 additions & 5 deletions lib/hijacker.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,10 @@ const path = require('path')

const bodyParser = require('body-parser')
const express = require('express')
const socketio = require('socket.io')

const config = require('./util/config')
const handleRoute = require('./util/handler')
const Sockets = require('./util/sockets')
const socketsMixin = require('./util/sockets')
const rules = require('./util/rules')
const util = require('./util/util')

Expand All @@ -26,7 +25,6 @@ class Hijacker {
this.conf = config.read(configObj)

// Set application variables
this.app.set('io', socketio(this.server))
this.app.set('ruleList', configObj.rules.map(rules.read))
this.app.set('conf', this.conf)

Expand All @@ -36,10 +34,9 @@ class Hijacker {
this.app.use(bodyParser.json())
this.app.use(util.requestCount())
this.app.all('*', handleRoute)

// Start server
this.server.listen(this.conf.port, () => {
this.sockets = new Sockets(this.app)
this._initSockets()
this.events.emit('started', this.conf.port)
})
}
Expand All @@ -57,4 +54,6 @@ class Hijacker {
}
}

socketsMixin(Hijacker)

module.exports = Hijacker
26 changes: 15 additions & 11 deletions lib/util/sockets.js
Original file line number Diff line number Diff line change
@@ -1,35 +1,39 @@
const socketio = require('socket.io')

const rules = require('./rules')

/**
* Set up listening to sockets from client
*
* @function initSockets
*/
class Sockets {
constructor(app) {
this.io = app.get('io')
this.ruleList = app.get('ruleList')
const socketsMixin = (Hijacker) => {
Hijacker.prototype._initSockets = function() {
let ruleList = this.app.get('ruleList')

this.io = socketio(this.server)
this.app.set('io', this.io)

// Send data needed for admin setup on setup
this.io.on('connection', (socket) => {
socket.emit('settings', {
rules: this.ruleList
rules: ruleList
})

// Update a rule
socket.on('UPDATE_RULE', (rule) => {
const index = this.ruleList.findIndex(r => r.id === rule.id)
this.ruleList[index] = rules.read(rule, true)
this.io.emit('UPDATE_RULE_LIST', this.ruleList)
const index = ruleList.findIndex(r => r.id === rule.id)
ruleList[index] = rules.read(rule, true)
this.io.emit('UPDATE_RULE_LIST', ruleList)
})

socket.on('ADD_RULE', (rule) => {
const newRule = rules.read(rule)
this.ruleList.push(newRule)
this.io.emit('UPDATE_RULE_LIST', this.ruleList)
ruleList.push(newRule)
this.io.emit('UPDATE_RULE_LIST', ruleList)
})
})
}
}

module.exports = Sockets
module.exports = socketsMixin

0 comments on commit 15b3ac0

Please sign in to comment.