-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
77 lines (57 loc) · 1.86 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
"use strict";
/*!
* Realtime Service - Server API
* Copyright(c) 2013 Owen Barnes <[email protected]>
* MIT Licensed
*/
function Server(service, transport) {
this.service = service;
this.transport = transport;
this.events = service.assigned.events;
}
Server.prototype.read = function(req) {
var self = this;
// Try to fetch Callback ID
var cbId = Number(req.attributes.callbackId);
if (this.service.use.json) req.message = JSON.parse(req.message);
this.onmessage(req.message, req, function(msg){
self.sendToSocketId(req.socketId, msg, {callbackId: cbId});
});
};
Server.prototype.sendToSocketIds = function(socketIds, msg, attrs) {
msg = this._prepareOutgoingMessage(msg, attrs);
if (typeof socketIds !== 'object') socketIds = [socketIds];
socketIds.forEach(function(socketId) {
this.transport.sendToSocketId(socketId, msg);
}, this);
};
// Alias
Server.prototype.sendToSocketId = Server.prototype.sendToSocketIds;
Server.prototype.broadcast = function(msg) {
msg = this._prepareOutgoingMessage(msg);
this.transport.broadcast(msg);
};
Server.prototype.log = function(){
var args = Array.prototype.slice.call(arguments);
this.service.log.call(this.service, args);
};
Server.prototype.debug = function(){
if (!this.service.assigned.options.debug) return;
var args = Array.prototype.slice.call(arguments);
args.unshift('DEBUG');
this.service.log.call(this.service, args);
};
// Private methods
Server.prototype._prepareOutgoingMessage = function(msg, attrs) {
if (this.service.use.json) msg = JSON.stringify(msg);
var buf = [this.service.assigned.id];
// Encode attributes into message if they exist
if (this.service.msgAttrs.length > 0) {
this.service.msgAttrs.map(function(attrName){
buf.push(attrs && attrs[attrName] || '');
});
}
buf.push(msg);
return buf.join('|');
};
module.exports = Server;