mirror of
https://github.com/tenrok/axios.git
synced 2026-05-15 11:59:42 +03:00
Adding transformers
This commit is contained in:
Vendored
+29
-5
File diff suppressed because one or more lines are too long
+28
-4
@@ -2,7 +2,9 @@ var Promise = require('es6-promise').Promise;
|
||||
|
||||
function axios(options) {
|
||||
options = merge({
|
||||
method: 'get'
|
||||
method: 'get',
|
||||
transformRequest: defaults.transformRequest,
|
||||
transformResponse: defaults.transformResponse
|
||||
}, options);
|
||||
|
||||
var promise = new Promise(function (resolve, reject) {
|
||||
@@ -10,7 +12,7 @@ function axios(options) {
|
||||
|
||||
function onload() {
|
||||
if (request.status >= 200 && request.status < 300) {
|
||||
resolve(parse(request.responseText));
|
||||
resolve(transformData(request.responseText, options.headers, options.transformResponse));
|
||||
} else {
|
||||
onerror();
|
||||
}
|
||||
@@ -41,13 +43,15 @@ function axios(options) {
|
||||
);
|
||||
|
||||
for (var key in headers) {
|
||||
request.setRequestHeader(key, headers[key]);
|
||||
if (headers.hasOwnProperty(key)) {
|
||||
request.setRequestHeader(key, headers[key]);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
reject(e);
|
||||
}
|
||||
|
||||
request.send(options.data ? JSON.stringify(options.data) : null);
|
||||
request.send(transformData(options.data, options.headers, options.transformRequest));
|
||||
});
|
||||
|
||||
promise.success = function (fn) {
|
||||
@@ -69,6 +73,14 @@ function axios(options) {
|
||||
|
||||
var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': 'application/json;charset=utf-8'};
|
||||
var defaults = axios.defaults = {
|
||||
transformRequest: [function (data) {
|
||||
return data ? JSON.stringify(data) : null;
|
||||
}],
|
||||
|
||||
transformResponse: [function (data) {
|
||||
return parse(data);
|
||||
}],
|
||||
|
||||
headers: {
|
||||
common: {'Accept': 'application/json, text/plain, */*'},
|
||||
patch: merge(CONTENT_TYPE_APPLICATION_JSON),
|
||||
@@ -77,6 +89,18 @@ var defaults = axios.defaults = {
|
||||
}
|
||||
};
|
||||
|
||||
function transformData(data, headers, fns) {
|
||||
if (typeof fns === 'function') {
|
||||
return fns(data, headers);
|
||||
}
|
||||
|
||||
forEach(fns, function (fn) {
|
||||
data = fn(data, headers);
|
||||
});
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
function parse(response) {
|
||||
try {
|
||||
return JSON.parse(response);
|
||||
|
||||
Reference in New Issue
Block a user