Skip to content

Commit

Permalink
Clean code and refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
brunnolou committed Dec 22, 2017
1 parent fd357b2 commit f74ce4a
Show file tree
Hide file tree
Showing 14 changed files with 1,637 additions and 232 deletions.
1 change: 1 addition & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"extends": "airbnb-base"
18 changes: 18 additions & 0 deletions app/cockpit.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const fetch = require('node-fetch');
const { cockpit } = require('./config');

const jsonRequest = (url, options = {}) => fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
...options,
}).then(res => res.json());

const fetchCockpit = qs =>
jsonRequest([cockpit.base, 'collections', 'get', qs.collection].join('/'), { qs });

module.exports = {
fetchCockpit,
jsonRequest,
};
18 changes: 18 additions & 0 deletions app/components/Broadcast.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const store = require('../store');

function Broadcast(action = 'updated', data) {
const connections = Object.values(store.activeConnections);

connections.forEach(({ connection }) => {
try {
const obj = JSON.stringify({ action, data });
console.log('obj: ', obj);

connection.sendUTF(obj);
} catch (error) {
console.log(error);
}
});
}

module.exports = Broadcast;
37 changes: 37 additions & 0 deletions app/components/Connect.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
const store = require('../store');

function Connect(connection, { resourceURL: { query } }) {
const id = store.globalCounter;

store.activeConnections[id] = {
collection: query.collection,
connection,
id,
query,
};

// Connected.
connection.sendUTF(JSON.stringify({ action: 'connected' }));
store.globalCounter += 1;

connection.on('message', (message) => {
if (message.type !== 'utf8') return;

// Broadcast.
Object.values(store.activeConnections).forEach(({ connection: conn, ...rest }) => {
conn.sendUTF(JSON.stringify({
action: 'updated',
message: message.utf8Data,
...rest,
}));
});
});

connection.on('close', (reasonCode, description) => {
console.log(`${new Date()} Peer ${connection.remoteAddress} disconnected. ${description}`);

delete store.activeConnections[connection.id];
});
}

module.exports = Connect;
7 changes: 5 additions & 2 deletions app/config.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
module.exports = {
httpPort: 3000,
requestProtocol: "refresh-protocol"
httpPort: 4000,
requestProtocol: 'refresh-protocol',
cockpit: {
base: 'http://ginetta.cockpit.rocks/frontendtf/api',
},
};
98 changes: 4 additions & 94 deletions app/index.js
Original file line number Diff line number Diff line change
@@ -1,96 +1,6 @@
const config = require("./config");
const http = require("http");
const express = require("express");
const app = express();
const httpServer = app.listen(config.httpPort);
const webSocketServer = require('./webSocketServer');
const webServer = require('./webServer');

// require('./wsServer')(httpServer);
const WebSocketServer = require("websocket").server;
const httpServer = webServer();

const wsServer = new WebSocketServer({
httpServer,
// You should not use autoAcceptConnections for production
// applications, as it defeats all standard cross-origin protection
// facilities built into the protocol and the browser. You should
// *always* verify the connection's origin and decide whether or not
// to accept it.
autoAcceptConnections: false
});

function originIsAllowed(origin) {
// put logic here to detect whether the specified origin is allowed.
return true;
}

globalCounter = 0;
allActiveConnections = {};

wsServer.on("request", function(request) {
if (!originIsAllowed(request.origin)) {
// Make sure we only accept requests from an allowed origin
request.reject();
console.log(
new Date() + " Connection from origin " + request.origin + " rejected."
);
return;
}

const connection = request.accept("refresh-protocol", request.origin);

var id = globalCounter++;
allActiveConnections[id] = connection;
connection.id = id;

connection.sendUTF(
JSON.stringify({
action: "connected"
})
);

connection.on("message", function(message) {
if (message.type !== "utf8") return;

connection.sendUTF(
JSON.stringify({
action: "connected",
message: message.utf8Data
})
);

// Broadcast.
Object.values(allActiveConnections).forEach(connection => {
connection.sendUTF(
JSON.stringify({
action: "connected",
message: message.utf8Data
})
);
});
});

connection.on("close", function(reasonCode, description) {
console.log(
new Date() + " Peer " + connection.remoteAddress + " disconnected."
);

delete allActiveConnections[connection.id];
});
});

app.use(express.static("public"));

app.all("/refresh/:collection?/:id?", function(req, res, next) {
const { collection, id } = req.params;

Object.values(allActiveConnections).forEach(connection => {
connection.sendUTF(
JSON.stringify({
action: "refreshed",
collection,
id
})
);
});

res.end();
});
webSocketServer(httpServer);
6 changes: 6 additions & 0 deletions app/store.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
const store = {
activeConnections: {},
globalCounter: 0,
};

module.exports = store;
30 changes: 30 additions & 0 deletions app/webServer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
const express = require('express');
const bodyParser = require('body-parser');

const config = require('./config');
const Broadcast = require('./components/Broadcast');

function webServer() {
const app = express();
const httpServer = app.listen(config.httpPort);

app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.post('/update', (req, res) => {
Broadcast('update', req.body);

res.end();
});

app.get('/update', (req, res) => {
Broadcast('update');

res.send('update was broadcasted');
});

return httpServer;
}

module.exports = webServer;
34 changes: 34 additions & 0 deletions app/webSocketServer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
const WebSocketServer = require('websocket').server;
const WebSocketRouter = require('websocket').router;
const Connect = require('./components/Connect');

const originIsAllowed = origin => true || origin;

function webSocketServer(httpServer) {
const wsServer = new WebSocketServer({
httpServer,
// You should not use autoAcceptConnections for production
// applications, as it defeats all standard cross-origin protection
// facilities built into the protocol and the browser. You should
// *always* verify the connection's origin and decide whether or not
// to accept it.
autoAcceptConnections: false,
});

// Ws Router.
const router = new WebSocketRouter();

router.attachServer(wsServer);

// Accepts all protocols.
router.mount('*', '*', (request) => {
if (!originIsAllowed(request.origin)) return request.reject();

const connection = request.accept(request.origin);

// @TODO check request.protocol
Connect(connection, request);
});
}

module.exports = webSocketServer;
69 changes: 0 additions & 69 deletions app/wsServer.js

This file was deleted.

Loading

0 comments on commit f74ce4a

Please sign in to comment.