Created
November 30, 2012 10:58
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is great, but it doesn't work if someone is using the .done() promise as a handler.