Files

122 lines
3.1 KiB
JavaScript

var SCSocket = require('./scsocket');
var scErrors = require('sc-errors');
var InvalidArgumentsError = scErrors.InvalidArgumentsError;
var _connections = {};
function getMultiplexId(options) {
var protocolPrefix = options.secure ? 'https://' : 'http://';
var queryString = '';
if (options.query) {
if (typeof options.query == 'string') {
queryString = options.query;
} else {
var queryArray = [];
var queryMap = options.query;
for (var key in queryMap) {
if (queryMap.hasOwnProperty(key)) {
queryArray.push(key + '=' + queryMap[key]);
}
}
if (queryArray.length) {
queryString = '?' + queryArray.join('&');
}
}
}
var host;
if (options.host) {
host = options.host;
} else {
host = options.hostname + ':' + options.port;
}
return protocolPrefix + host + options.path + queryString;
}
function isUrlSecure() {
return global.location && location.protocol == 'https:';
}
function getPort(options, isSecureDefault) {
var isSecure = options.secure == null ? isSecureDefault : options.secure;
return options.port || (global.location && location.port ? location.port : isSecure ? 443 : 80);
}
function connect(options) {
var self = this;
options = options || {};
if (options.host && options.port) {
throw new InvalidArgumentsError('The host option should already include the' +
' port number in the format hostname:port - Because of this, the host and port options' +
' cannot be specified together; use the hostname option instead');
}
var isSecureDefault = isUrlSecure();
var opts = {
port: getPort(options, isSecureDefault),
hostname: global.location && location.hostname,
path: '/socketcluster/',
secure: isSecureDefault,
autoConnect: true,
autoReconnect: true,
autoProcessSubscriptions: true,
connectTimeout: 20000,
ackTimeout: 10000,
timestampRequests: false,
timestampParam: 't',
authEngine: null,
authTokenName: 'socketCluster.authToken',
binaryType: 'arraybuffer',
multiplex: true,
cloneData: false
};
for (var i in options) {
if (options.hasOwnProperty(i)) {
opts[i] = options[i];
}
}
var multiplexId = getMultiplexId(opts);
if (opts.multiplex === false) {
return new SCSocket(opts);
}
if (_connections[multiplexId]) {
_connections[multiplexId].connect();
} else {
_connections[multiplexId] = new SCSocket(opts);
}
return _connections[multiplexId];
}
function destroy(options) {
var self = this;
options = options || {};
var isSecureDefault = isUrlSecure();
var opts = {
port: getPort(options, isSecureDefault),
hostname: global.location && location.hostname,
path: '/socketcluster/',
secure: isSecureDefault
};
for (var i in options) {
if (options.hasOwnProperty(i)) {
opts[i] = options[i];
}
}
var multiplexId = getMultiplexId(opts);
var socket = _connections[multiplexId];
if (socket) {
socket.disconnect();
}
delete _connections[multiplexId];
}
module.exports = {
connect: connect,
destroy: destroy,
connections: _connections
};