提交 cec3482f 编写于 作者: M Matt Zabriskie

Moving utility functions into utils

上级 ceca9ced
......@@ -34,7 +34,7 @@ module.exports = function(grunt) {
},
nodeunit: {
all: ['test/unit/*.js']
all: ['test/unit/**/*.js']
},
webpack: generateWebpackConfig(),
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
var Promise = require('es6-promise').Promise;
var buildUrl = require('./buildUrl');
var defaults = require('./defaults');
var forEach = require('./forEach');
var merge = require('./merge');
var parseHeaders = require('./parseHeaders');
var transformData = require('./transformData');
var utils = require('./utils');
var axios = module.exports = function axios(options) {
options = merge({
options = utils.merge({
method: 'get',
transformRequest: defaults.transformRequest,
transformResponse: defaults.transformResponse
......@@ -57,13 +56,13 @@ var axios = module.exports = function axios(options) {
};
// Merge headers and add to request
var headers = merge(
var headers = utils.merge(
defaults.headers.common,
defaults.headers[options.method] || {},
options.headers || {}
);
forEach(headers, function (val, key) {
utils.forEach(headers, function (val, key) {
// Remove Content-Type if data is undefined
if (typeof data === 'undefined' && key.toLowerCase() === 'content-type') {
delete headers[key];
......@@ -121,9 +120,9 @@ createShortMethods('delete', 'get', 'head');
createShortMethodsWithData('post', 'put', 'patch');
function createShortMethods() {
forEach(arguments, function (method) {
utils.forEach(arguments, function (method) {
axios[method] = function (url, options) {
return axios(merge(options || {}, {
return axios(utils.merge(options || {}, {
method: method,
url: url
}));
......@@ -132,9 +131,9 @@ function createShortMethods() {
}
function createShortMethodsWithData() {
forEach(arguments, function (method) {
utils.forEach(arguments, function (method) {
axios[method] = function (url, data, options) {
return axios(merge(options || {}, {
return axios(utils.merge(options || {}, {
method: method,
url: url,
data: data
......
'use strict';
var forEach = require('./forEach');
var utils = require('./utils');
function encode(val) {
return encodeURIComponent(val).
......@@ -18,19 +18,19 @@ module.exports = function buildUrl(url, params) {
var parts = [];
forEach(params, function (val, key) {
utils.forEach(params, function (val, key) {
if (val === null || typeof val === 'undefined') {
return;
}
if (Object.prototype.toString.call(val) !== '[object Array]') {
if (!utils.isArray(val)) {
val = [val];
}
forEach(val, function (v) {
if (Object.prototype.toString.call(v) === '[object Date]') {
utils.forEach(val, function (v) {
if (utils.isDate(v)) {
v = v.toISOString();
}
else if (typeof v === 'object') {
else if (utils.isObject(v)) {
v = JSON.stringify(v);
}
parts.push(encode(key) + '=' + encode(v));
......
'use strict';
var merge = require('./merge');
var utils = require('./utils');
var toString = Object.prototype.toString;
var JSON_START = /^\s*(\[|\{[^\{])/;
var JSON_END = /[\}\]]\s*$/;
var PROTECTION_PREFIX = /^\)\]\}',?\n/;
......@@ -12,9 +11,9 @@ var CONTENT_TYPE_APPLICATION_JSON = {
module.exports = {
transformRequest: [function (data) {
return data !== null && typeof data === 'object' &&
toString.call(data) !== '[object File]' &&
toString.call(data) !== '[object Blob]' ?
return utils.isObject(data) &&
!utils.isFile(data) &&
!utils.isBlob(data) ?
JSON.stringify(data) : null;
}],
......@@ -32,9 +31,9 @@ module.exports = {
common: {
'Accept': 'application/json, text/plain, */*'
},
patch: merge(CONTENT_TYPE_APPLICATION_JSON),
post: merge(CONTENT_TYPE_APPLICATION_JSON),
put: merge(CONTENT_TYPE_APPLICATION_JSON)
patch: utils.merge(CONTENT_TYPE_APPLICATION_JSON),
post: utils.merge(CONTENT_TYPE_APPLICATION_JSON),
put: utils.merge(CONTENT_TYPE_APPLICATION_JSON)
},
xsrfCookiName: 'XSRF-TOKEN',
......
'use strict';
function isArrayLike(obj) {
return obj.constructor === Array || typeof obj.callee === 'function';
}
/**
* Iterate over an Array or an Object invoking a function for each item.
*
* If `obj` is an Array or arguments callback will be called passing
* the value, index, and complete array for each item.
*
* If 'obj' is an Object callback will be called passing
* the value, key, and complete object for each property.
*
* @param {Object|Array} obj The object to iterate
* @param {Function} fn The callback to invoke for each item
*/
module.exports = function forEach(obj, fn) {
// Don't bother if no value provided
if (obj === null || typeof obj === 'undefined') {
return;
}
var isArray = isArrayLike(obj);
// Force an array if not already something iterable
if (typeof obj !== 'object' && !isArray) {
obj = [obj];
}
// Iterate over array values
if (isArray) {
for (var i=0, l=obj.length; i<l; i++) {
fn.call(null, obj[i], i, obj);
}
}
// Iterate over object keys
else {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
fn.call(null, obj[key], key, obj);
}
}
}
};
\ No newline at end of file
var forEach = require('./forEach');
/**
* Accepts varargs expecting each argument to be an object, then
* immutably merges the properties of each object and returns result.
*
* When multiple objects contain the same key the later object in
* the arguments list will take precedence.
*
* Example:
*
* ```js
* var result = merge({foo: 123}, {foo: 456});
* console.log(result.foo); // outputs 456
* ```
*
* @param {Object} obj1 Object to merge
* @returns {Object} Result of all merge properties
*/
module.exports = function merge(obj1/*, obj2, obj3, ...*/) {
var result = {};
forEach(arguments, function (obj) {
forEach(obj, function (val, key) {
result[key] = val;
});
});
return result;
};
\ No newline at end of file
'use strict';
var forEach = require('./forEach');
function trim(str) {
return str.replace(/^\s*/, '').replace(/\s*$/, '');
}
var utils = require('./utils');
/**
* Parse headers into an object
......@@ -24,10 +20,10 @@ module.exports = function parseHeaders(headers) {
if (!headers) return parsed;
forEach(headers.split('\n'), function(line) {
utils.forEach(headers.split('\n'), function(line) {
i = line.indexOf(':');
key = trim(line.substr(0, i)).toLowerCase();
val = trim(line.substr(i + 1));
key = utils.trim(line.substr(0, i)).toLowerCase();
val = utils.trim(line.substr(i + 1));
if (key) {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
......
'use strict';
var forEach = require('./forEach');
var utils = require('./utils');
/**
* Transform the data for a request or a response
......@@ -11,7 +11,7 @@ var forEach = require('./forEach');
* @returns {*} The resulting transformed data
*/
module.exports = function transformData(data, headers, fns) {
forEach(fns, function (fn) {
utils.forEach(fns, function (fn) {
data = fn(data, headers);
});
......
// utils is a library of generic helper functions non-specific to axios
var toString = Object.prototype.toString;
/**
* Determine if a value is an Array
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an Array, otherwise false
*/
function isArray(val) {
return toString.call(val) === '[object Array]';
}
/**
* Determine if a value is an Object
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an Object, otherwise false
*/
function isObject(val) {
return val !== null && typeof val === 'object';
}
/**
* Determine if a value is a Date
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Date, otherwise false
*/
function isDate(val) {
return toString.call(val) === '[object Date]';
}
/**
* Determine if a value is a File
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a File, otherwise false
*/
function isFile(val) {
return toString.call(val) === '[object File]';
}
/**
* Determine if a value is a Blob
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Blob, otherwise false
*/
function isBlob(val) {
return toString.call(val) !== '[object Blob]';
}
/**
* Trim excess whitespace off the beginning and end of a string
*
* @param {String} str The String to trim
* @returns {String} The String freed of excess whitespace
*/
function trim(str) {
return str.replace(/^\s*/, '').replace(/\s*$/, '');
}
/**
* Iterate over an Array or an Object invoking a function for each item.
*
* If `obj` is an Array or arguments callback will be called passing
* the value, index, and complete array for each item.
*
* If 'obj' is an Object callback will be called passing
* the value, key, and complete object for each property.
*
* @param {Object|Array} obj The object to iterate
* @param {Function} fn The callback to invoke for each item
*/
function forEach(obj, fn) {
// Don't bother if no value provided
if (obj === null || typeof obj === 'undefined') {
return;
}
// Check if obj is array-like
var isArray = obj.constructor === Array || typeof obj.callee === 'function';
// Force an array if not already something iterable
if (typeof obj !== 'object' && !isArray) {
obj = [obj];
}
// Iterate over array values
if (isArray) {
for (var i=0, l=obj.length; i<l; i++) {
fn.call(null, obj[i], i, obj);
}
}
// Iterate over object keys
else {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
fn.call(null, obj[key], key, obj);
}
}
}
}
/**
* Accepts varargs expecting each argument to be an object, then
* immutably merges the properties of each object and returns result.
*
* When multiple objects contain the same key the later object in
* the arguments list will take precedence.
*
* Example:
*
* ```js
* var result = merge({foo: 123}, {foo: 456});
* console.log(result.foo); // outputs 456
* ```
*
* @param {Object} obj1 Object to merge
* @returns {Object} Result of all merge properties
*/
function merge(obj1/*, obj2, obj3, ...*/) {
var result = {};
forEach(arguments, function (obj) {
forEach(obj, function (val, key) {
result[key] = val;
});
});
return result;
}
module.exports = {
isArray: isArray,
isObject: isObject,
isDate: isDate,
isFile: isFile,
isBlob: isBlob,
forEach: forEach,
merge: merge,
trim: trim
};
\ No newline at end of file
var forEach = require('../../lib/forEach');
var forEach = require('../../../lib/utils').forEach;
module.exports = {
testArray: function (test) {
......
var utils = require('../../../lib/utils');
module.exports = {
testIsArray: function (test) {
test.equals(utils.isArray([]), true);
test.equals(utils.isArray({length: 5}), false);
test.done();
},
testIsObject: function (test) {
test.equals(utils.isObject({}), true);
test.equals(utils.isObject(null), false);
test.done();
},
testIsDate: function (test) {
test.equals(utils.isDate(new Date()), true);
test.equals(utils.isDate(Date.now()), false);
test.done();
}
};
\ No newline at end of file
var merge = require('../../lib/merge');
var merge = require('../../../lib/utils').merge;
module.exports = {
testImmutability: function (test) {
......
var trim = require('../../../lib/utils').trim;
module.exports = {
testTrim: function (test) {
test.equals(trim(' foo '), 'foo');
test.done();
},
testTrimTab: function (test) {
test.equals(trim('\tfoo'), 'foo');
test.done();
}
};
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册