@emartech/faye-redis-sharded
Version:
Redis backend engine for Faye with support for sharding
60 lines (47 loc) • 1.91 kB
JavaScript
Faye.Transport.XHR = Faye.extend(Faye.Class(Faye.Transport, {
encode: function(envelopes) {
var messages = Faye.map(envelopes, function(e) { return e.message });
return Faye.toJSON(messages);
},
request: function(envelopes) {
var href = this.endpoint.href,
xhr = Faye.ENV.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest(),
self = this;
xhr.open('POST', href, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Pragma', 'no-cache');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
var headers = this._client.headers;
for (var key in headers) {
if (!headers.hasOwnProperty(key)) continue;
xhr.setRequestHeader(key, headers[key]);
}
var abort = function() { xhr.abort() };
if (Faye.ENV.onbeforeunload !== undefined) Faye.Event.on(Faye.ENV, 'beforeunload', abort);
xhr.onreadystatechange = function() {
if (!xhr || xhr.readyState !== 4) return;
var parsedMessage = null,
status = xhr.status,
text = xhr.responseText,
successful = (status >= 200 && status < 300) || status === 304 || status === 1223;
if (Faye.ENV.onbeforeunload !== undefined) Faye.Event.detach(Faye.ENV, 'beforeunload', abort);
xhr.onreadystatechange = function() {};
xhr = null;
if (!successful) return self.handleError(envelopes);
try {
parsedMessage = JSON.parse(text);
} catch (e) {}
if (parsedMessage)
self.receive(envelopes, parsedMessage);
else
self.handleError(envelopes);
};
xhr.send(this.encode(envelopes));
return xhr;
}
}), {
isUsable: function(client, endpoint, callback, context) {
callback.call(context, Faye.URI.isSameOrigin(endpoint));
}
});
Faye.Transport.register('long-polling', Faye.Transport.XHR);