@emartech/faye-redis-sharded
Version:
Redis backend engine for Faye with support for sharding
70 lines (57 loc) • 1.98 kB
JavaScript
Faye.Transport.CORS = Faye.extend(Faye.Class(Faye.Transport, {
encode: function(envelopes) {
var messages = Faye.map(envelopes, function(e) { return e.message });
return 'message=' + encodeURIComponent(Faye.toJSON(messages));
},
request: function(envelopes) {
var xhrClass = Faye.ENV.XDomainRequest ? XDomainRequest : XMLHttpRequest,
xhr = new xhrClass(),
headers = this._client.headers,
self = this,
key;
xhr.open('POST', Faye.URI.stringify(this.endpoint), true);
if (xhr.setRequestHeader) {
xhr.setRequestHeader('Pragma', 'no-cache');
for (key in headers) {
if (!headers.hasOwnProperty(key)) continue;
xhr.setRequestHeader(key, headers[key]);
}
}
var cleanUp = function() {
if (!xhr) return false;
xhr.onload = xhr.onerror = xhr.ontimeout = xhr.onprogress = null;
xhr = null;
};
xhr.onload = function() {
var parsedMessage = null;
try {
parsedMessage = JSON.parse(xhr.responseText);
} catch (e) {}
cleanUp();
if (parsedMessage)
self.receive(envelopes, parsedMessage);
else
self.handleError(envelopes);
};
xhr.onerror = xhr.ontimeout = function() {
cleanUp();
self.handleError(envelopes);
};
xhr.onprogress = function() {};
xhr.send(this.encode(envelopes));
return xhr;
}
}), {
isUsable: function(client, endpoint, callback, context) {
if (Faye.URI.isSameOrigin(endpoint))
return callback.call(context, false);
if (Faye.ENV.XDomainRequest)
return callback.call(context, endpoint.protocol === Faye.ENV.location.protocol);
if (Faye.ENV.XMLHttpRequest) {
var xhr = new Faye.ENV.XMLHttpRequest();
return callback.call(context, xhr.withCredentials !== undefined);
}
return callback.call(context, false);
}
});
Faye.Transport.register('cross-origin-long-polling', Faye.Transport.CORS);