Skip to content

Replace Socket.io with Primus + µWS #2569

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
May 14, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Gruntfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ module.exports = function (grunt) {
testing: 'jasmine',
auth: true,
oauth: ['googleAuth', 'twitterAuth'],
socketio: true
ws: true
};

var deps = [
Expand Down
2 changes: 1 addition & 1 deletion docs/01_Getting_Started/04_Project_Overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ webpack.make.js // main file for Webpack configuration
│ local.env.js // ignored by Git
│ local.env.sample.js // sensitive environment variables are stored here, and added at server start. Copy to `local.env.js`.
│ seed.js // re-seeds database with fresh data
socketio.js // Socket IO configuration / imports
websockets.js // WebSocket configuration / imports
└───environment
development.js
Expand Down
10 changes: 5 additions & 5 deletions src/generators/app/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -270,14 +270,14 @@ export class Generator extends Base {
}]
}, {
type: 'confirm',
name: 'socketio',
message: 'Would you like to use socket.io?',
name: 'ws',
message: 'Would you like to use WebSockets?',
// to-do: should not be dependent on ODMs
when: answers => answers.odms && answers.odms.length !== 0,
default: true
}]).then(answers => {
if(answers.socketio) this.filters.socketio = true;
insight.track('socketio', !!answers.socketio);
if(answers.ws) this.filters.ws = true;
insight.track('ws', !!answers.ws);

if(answers.auth) this.filters.auth = true;
insight.track('auth', !!answers.auth);
Expand Down Expand Up @@ -374,7 +374,7 @@ export class Generator extends Base {
this.config.set('pluralizeRoutes', true);

this.config.set('insertSockets', true);
this.config.set('registerSocketsFile', 'server/config/socketio.js');
this.config.set('registerSocketsFile', 'server/config/websockets.js');
this.config.set('socketsNeedle', '// Insert sockets below');

this.config.set('insertModels', true);
Expand Down
11 changes: 5 additions & 6 deletions src/generators/endpoint/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ export class Generator extends NamedBase {
end() {
if(this.config.get('insertRoutes')) {
var routesFile = this.config.get('registerRoutesFile');
var reqPath = this.relativeRequire(this.routeDest, routesFile);
let reqPath = this.relativeRequire(this.routeDest, routesFile);
var routeConfig = {
file: routesFile,
needle: this.config.get('routesNeedle'),
Expand All @@ -108,23 +108,22 @@ export class Generator extends NamedBase {
this.rewriteFile(routeConfig);
}

if(this.filters.socketio && this.config.get('insertSockets')) {
if(this.filters.ws && this.config.get('insertSockets')) {
var socketsFile = this.config.get('registerSocketsFile');
var reqPath = this.relativeRequire(this.routeDest + '/' + this.basename +
'.socket', socketsFile);
let reqPath = this.relativeRequire(this.routeDest + '/' + this.basename + '.socket', socketsFile);
var socketConfig = {
file: socketsFile,
needle: this.config.get('socketsNeedle'),
splicable: [
`require('${reqPath}').register(socket);`
`require('${reqPath}').register,`
]
};
this.rewriteFile(socketConfig);
}

if(this.filters.sequelize && this.config.get('insertModels')) {
var modelsFile = this.config.get('registerModelsFile');
var reqPath = this.relativeRequire(`${this.routeDest}/${this.basename}.model`, modelsFile);
let reqPath = this.relativeRequire(`${this.routeDest}/${this.basename}.model`, modelsFile);
var modelConfig = {
file: modelsFile,
needle: this.config.get('modelsNeedle'),
Expand Down
2 changes: 1 addition & 1 deletion src/test/endpoint.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const defaultOptions = {
odms: ['mongoose'],
auth: true,
oauth: [],
socketio: true
ws: true
};

function runEndpointGen(name, opt={}) {
Expand Down
4 changes: 2 additions & 2 deletions src/test/fixtures/.yo-rc.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"routesBase": "/api/",
"pluralizeRoutes": true,
"insertSockets": true,
"registerSocketsFile": "server/config/socketio.js",
"registerSocketsFile": "server/config/websockets.js",
"socketsNeedle": "// Insert sockets below",
"insertModels": true,
"registerModelsFile": "server/sqldb/index.js",
Expand All @@ -21,7 +21,7 @@
"uirouter": true,
"bootstrap": true,
"uibootstrap": true,
"socketio": true,
"ws": true,
"auth": true,
"models": true,
"mongooseModels": true,
Expand Down
8 changes: 4 additions & 4 deletions src/test/get-expected-files.js
Original file line number Diff line number Diff line change
Expand Up @@ -203,18 +203,18 @@ export function app(options) {
'client/components/oauth-buttons/oauth-buttons.' + stylesheet,
'client/components/oauth-buttons/oauth-buttons.' + markup,
'client/components/oauth-buttons/oauth-buttons.component.' + script,
'client/components/oauth-buttons/oauth-buttons.component.spec.' + script,
'client/components/oauth-buttons/oauth-buttons.component.spec.' + script,
'e2e/components/oauth-buttons/oauth-buttons.po.js'
]);
}

/* Socket.IO */
if (options.socketio) {
/* WebSockets */
if (options.ws) {
files = files.concat([
'client/components/socket/socket.service.' + script,
'client/components/socket/socket.mock.' + script,
'server/api/thing/thing.socket.js',
'server/config/socketio.js'
'server/config/websockets.js'
]);
}

Expand Down
8 changes: 4 additions & 4 deletions src/test/main.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const defaultOptions = {
odms: ['mongoose'],
auth: true,
oauth: [],
socketio: true
ws: true
};
const TEST_DIR = __dirname;

Expand Down Expand Up @@ -198,7 +198,7 @@ describe('angular-fullstack:app', function() {
odms: ['mongoose'],
auth: true,
oauth: ['twitterAuth', 'facebookAuth', 'googleAuth'],
socketio: true,
ws: true,
bootstrap: true,
uibootstrap: true
};
Expand Down Expand Up @@ -270,7 +270,7 @@ describe('angular-fullstack:app', function() {
odms: ['sequelize'],
auth: true,
oauth: ['twitterAuth', 'facebookAuth', 'googleAuth'],
socketio: true,
ws: true,
bootstrap: true,
uibootstrap: true
};
Expand Down Expand Up @@ -343,7 +343,7 @@ describe('angular-fullstack:app', function() {
odms: [],
auth: false,
oauth: [],
socketio: false,
ws: false,
bootstrap: false,
uibootstrap: false
};
Expand Down
8 changes: 4 additions & 4 deletions templates/app/_package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,10 @@
"passport-local": "^1.0.0",<% } %><% if(filters.facebookAuth) { %>
"passport-facebook": "^2.0.0",<% } %><% if(filters.twitterAuth) { %>
"passport-twitter": "^1.0.3",<% } %><% if(filters.googleAuth) { %>
"passport-google-oauth20": "^1.0.0",<% } %><% if(filters.socketio) { %>
"socket.io": "^1.3.5",
"socket.io-client": "^1.3.5",
"socketio-jwt": "^4.2.0",<% } %>
"passport-google-oauth20": "^1.0.0",<% } %><% if(filters.ws) { %>
"primus": "^7.0.1",
"primus-emit": "^1.0.0",
"uws": "^0.14.5",<% } %>
"serve-favicon": "^2.3.0",
"shrink-ray": "^0.1.3"
},
Expand Down
20 changes: 10 additions & 10 deletions templates/app/client/app/main/main.component.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Component, OnInit<% if(filters.socketio) { %>, OnDestroy<% } %> } from '@angular/core';
import { Component, OnInit<% if(filters.ws) { %>, OnDestroy<% } %> } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { SocketService } from '../../components/socket/socket.service';
Expand All @@ -8,34 +8,34 @@ import { SocketService } from '../../components/socket/socket.service';
template: require('./main.<%=templateExt%>'),
styles: [require('./main.<%=styleExt%>')],
})
export class MainComponent implements OnInit<% if(filters.socketio) { %>, OnDestroy<% } %> {
<%_ if(filters.socketio) { -%>
export class MainComponent implements OnInit<% if(filters.ws) { %>, OnDestroy<% } %> {
<%_ if(filters.ws) { -%>
SocketService;<% } %>
awesomeThings = [];
<%_ if(filters.models) { -%>
newThing = '';<% } %>

<%_ if(filters.babel) { -%>
static parameters = [Http, SocketService];<% } %>
constructor(<%= private() %>http: Http<% if(filters.socketio) { %>, <%= private() %>socketService: SocketService<% } %>) {
constructor(<%= private() %>http: Http<% if(filters.ws) { %>, <%= private() %>socketService: SocketService<% } %>) {
this.Http = http;
<%_ if(filters.socketio) { -%>
<%_ if(filters.ws) { -%>
this.SocketService = socketService;<% } %>
}

ngOnInit() {
this.Http.get('/api/things')
.map(res => {
return res.json();
<%_ if(filters.socketio) { -%>
// this.SocketService.syncUpdates('thing', this.awesomeThings);<% } %>
})
.catch(err => Observable.throw(err.json().error || 'Server error'))
.subscribe(things => {
this.awesomeThings = things;
<%_ if(filters.ws) { -%>
this.SocketService.syncUpdates('thing', this.awesomeThings);<% } %>
});
}<% if (filters.models) { %>
<%_ if(filters.socketio) { %>
<%_ if(filters.ws) { %>

ngOnDestroy() {
this.SocketService.unsyncUpdates('thing');
Expand All @@ -50,7 +50,7 @@ export class MainComponent implements OnInit<% if(filters.socketio) { %>, OnDest
.map(res => res.json())
.catch(err => Observable.throw(err.json().error || 'Server error'))
.subscribe(thing => {
this.awesomeThings.push(thing);
console.log('Added Thing:', thing);
});
}
}
Expand All @@ -60,7 +60,7 @@ export class MainComponent implements OnInit<% if(filters.socketio) { %>, OnDest
.map(res => res.json())
.catch(err => Observable.throw(err.json().error || 'Server error'))
.subscribe(() => {
this.awesomeThings.splice(this.awesomeThings.findIndex(el => el._id === thing._id), 1);
console.log('Deleted Thing');
});
}<% } %>
}
6 changes: 3 additions & 3 deletions templates/app/client/app/main/main.component.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ describe('Component: MainComponent', function() {
beforeEach(angular.mock.module(main));
<%_ if (filters.uirouter) { _%>
beforeEach(angular.mock.module('stateMock'));<% } _%>
<%_ if (filters.socketio) { _%>
<%_ if (filters.ws) { _%>
beforeEach(angular.mock.module('socketMock'));<% } %>

var scope;
Expand All @@ -22,7 +22,7 @@ describe('Component: MainComponent', function() {
$http,
$componentController,
$rootScope<% if (filters.uirouter) {%>,
$state<% } %><% if (filters.socketio) {%>,
$state<% } %><% if (filters.ws) {%>,
socket<% } %>) {
$httpBackend = _$httpBackend_;
$httpBackend.expectGET('/api/things')
Expand All @@ -32,7 +32,7 @@ describe('Component: MainComponent', function() {
state = $state;<% } %>
mainComponent = $componentController('main', {
$http: $http,
$scope: scope<% if (filters.socketio) {%>,
$scope: scope<% if (filters.ws) {%>,
socket: socket<% } %>
});
}));
Expand Down
2 changes: 1 addition & 1 deletion templates/app/client/app/main/main.html
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ <h1 class="page-header">Features:</h1>
</a></li>
</ul>
</div>
</div><% if (filters.socketio) { %>
</div><% if (filters.ws) { %>

<form class="thing-form">
<label>Syncs in realtime across clients</label>
Expand Down
4 changes: 2 additions & 2 deletions templates/app/client/app/main/main.module.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { RouterModule, Routes } from '@angular/router';<% } %>
import { TooltipModule } from 'ng2-bootstrap';<% } %>

import { MainComponent } from './main.component';
<%_ if(filters.socketio) { -%>
<%_ if(filters.ws) { -%>
import { SocketService } from '../../components/socket/socket.service';<% } %>

<%_ if(filters.ngroute) { _%>
Expand Down Expand Up @@ -37,7 +37,7 @@ export const STATES = [
declarations: [
MainComponent,
],
<%_ if(filters.socketio) { -%>
<%_ if(filters.ws) { -%>
providers: [
SocketService,
],<% } %>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,32 @@
'use strict';
import Primus from './primus';
import primusEmit from 'primus-emit';
import { Injectable } from '@angular/core';
import { noop, find, remove } from 'lodash';
import io from 'socket.io-client';
import constants from '../../app/app.constants';

@Injectable()
export class SocketService {
socket;
primus;

constructor() {
this.socket = io(constants.env === 'development' ? `localhost:${constants.port}` : '', {
// Send auth token on connection, you will need to DI the Auth service above
// 'query': 'token=' + Auth.getToken()
const primus = Primus.connect();
primus.plugin('emit', primusEmit);

primus.on('open', function open() {
console.log('Connection opened');
});

if(process.env.NODE_ENV === 'development') {
primus.on('data', function message(data) {
console.log('Socket:', data);
});
}

primus.on('info', data => {
console.log('info:', data);
});

this.primus = primus;
}

/**
Expand All @@ -29,10 +43,11 @@ export class SocketService {
/**
* Syncs item creation/updates on 'model:save'
*/
this.socket.on(`${modelName}:save`, function(item) {
var oldItem = find(array, {_id: item._id});
var index = array.indexOf(oldItem);
var event = 'created';
this.primus.on(`${modelName}:save`, item => {
console.log(item);
let oldItem = find(array, {_id: item._id});
let index = array.indexOf(oldItem);
let event = 'created';

// replace oldItem if it exists
// otherwise just add item to the collection
Expand All @@ -49,10 +64,9 @@ export class SocketService {
/**
* Syncs removed items on 'model:remove'
*/
this.socket.on(`${modelName}:remove`, function(item) {
var event = 'deleted';
this.primus.on(`${modelName}:remove`, item => {
remove(array, {_id: item._id});
cb(event, item, array);
cb('deleted', item, array);
});
}

Expand All @@ -62,7 +76,7 @@ export class SocketService {
* @param modelName
*/
unsyncUpdates(modelName) {
this.socket.removeAllListeners(`${modelName}:save`);
this.socket.removeAllListeners(`${modelName}:remove`);
this.primus.removeAllListeners(`${modelName}:save`);
this.primus.removeAllListeners(`${modelName}:remove`);
}
}
Loading