Atmosphere/atmosphere — Issue #175: better support to track headers for extensions
Author: haed
Created: 2012-01-31 20:11:23+00:00
State: open

Some atmosphere extensions need to track own headers, also the header-handling in the atmosphere.js could be improved with the following steps:

1. reponse.headers should be an associative array (instead of a string):

- add a helping method:

var parseHeaders = function(headerString) {
var headers = {};
jQuery.each(headerString.split("\n"), function(idx, token) {
if (token.trim().length > 0) {
var a = token.split(":");
headers[jQuery.trim(a[0])] = jQuery.trim(a[1]);
}
});
return headers;
};

- initialize response.headers with {} instead of []
- replace all occurrences of

response.headers = ajaxRequest.getAllResponseHeaders()
with
response.headers = parseHeaders(ajaxRequest.getAllResponseHeaders());

2. add support to add custom headers in a nice configurable way:

change header handling in the doRequest()-method from:
for (var x in request.headers) {
ajaxRequest.setRequestHeader(x, request.headers[x]);
}
to:
jQuery.each(request.headers, function(name, value) {
var h = jQuery.isFunction(value) ? value.call(this, ajaxRequest, request, create) : value;
if (h) {
ajaxRequest.setRequestHeader(name, h);
}
});

now we can simply add some custom/generic (depends on server response) parameters, here is an example (used in haed.notification):

jQuery.atmosphere.subscribe(url, null, {
headers: {
"test": "hello",
"X-Cache-Serial": function(ajaxRequest, request, create) {
if (jQuery.atmosphere.response.headers) {
return jQuery.atmosphere.response.headers["X-Cache-Serial"];
}
}
}});

Also atmosphere intern header handling could be use this pattern (same logic, less bugs), simply configure the atmosphere-header handling in the initialization step (initial values of request.headers in the merge-step).

Also it would be nice if attachHeadersAsQueryString() use the same/similar approach (using functions/values set in request.headers to extend query string).

I could prepare an initial patch.