Skip to content

Instantly share code, notes, and snippets.

@topliceanu
Created November 30, 2012 10:58
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save topliceanu/4175125 to your computer and use it in GitHub Desktop.
Save topliceanu/4175125 to your computer and use it in GitHub Desktop.
A centralized way to modify jquery ajax responses. Usefull in testing where you need semi-mocks
var alterResponse = function (opts) {
/**
* Function modifies $.ajax responses
* by allowing you to modify ajax response object before each bound success callback.
* Currently it supports only `success` callbacks, `error` and `complete` support to come.
* @param {RegExp} opts.urlMatch - use this to filter calls by url
* @param {String} opts.dataType - Optional - use this to filter calls by response type
* @param {Function} opts.successWrapper - function that gets called before each ajax callback
* - function (options:Object, originalOptions:Object, jqXHR:jQuery.XHR, originalSuccess: Function)
*/
var callback = function (options, originalOptions, jqXHR) {
var check = true;
if (opts.urlMatch && !options.url.match(opts.urlMatch)) check = false;
if (opts.typeMatch && !options.type.match(opts.typeMatch)) check = false;
if (check) {
var originalSuccess = originalOptions.success || options.success;
var next = function (data) {
originalSuccess(data);
};
originalOptions.success = options.success = function () {
// In your wrapper, call next() after you changed the response.
opts.successWrapper.call(null, options, originalOptions, jqXHR, next);
};
}
};
if (opts.dataTypes) {
$.ajaxPrefilter(opts.dataTypes, callback);
}
else {
$.ajaxPrefilter(callback);
}
};
alterResponse({
urlMatch: /user/g,
typeMatch: /get/gi,
successWrapper: function (options, originalOptions, jqXHR, next) {
var response = JSON.parse(jqXHR.responseText);
response.name = 'Some other name'
next(response);
}
});
@derekrprice
Copy link

This is great, but it doesn't work if someone is using the .done() promise as a handler.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment