mirror of
https://github.com/tenrok/axios.git
synced 2026-06-20 20:00:40 +03:00
Axios ES2017 (#4787)
* Added AxiosHeaders class; * Fixed README.md href; * Fixed a potential bug with headers normalization; * Fixed a potential bug with headers normalization; Refactored accessor building routine; Refactored default transforms; Removed `normalizeHeaderName` helper; * Added `Content-Length` accessor; Added missed `has` accessor to TS types; * Added `AxiosTransformStream` class; Added progress capturing ability for node.js environment; Added `maxRate` option to limit the data rate in node.js environment; Refactored event handled by `onUploadProgress` && `onDownloadProgress` listeners in browser environment; Added progress & data rate tests for the http adapter; Added response stream aborting test; Added a manual progress capture test for the browser; Updated TS types; Added TS tests; Refactored request abort logic for the http adapter; Added ability to abort the response stream; * Remove `stream/promises` & `timers/promises` modules usage in tests; * Use `abortcontroller-polyfill`; * Fixed AxiosTransformStream dead-lock in legacy node versions; Fixed CancelError emitting in streams; * Reworked AxiosTransformStream internal logic to optimize memory consumption; Added throwing an error if the request stream was silently destroying (without error) Refers to #3966; * Treat the destruction of the request stream as a cancellation of the request; Fixed tests; * Emit `progress` event in the next tick; * Initial refactoring; * Refactored Mocha tests to use ESM; * Refactored Karma tests to use rollup preprocessor & ESM; Replaced grunt with gulp; Improved dev scripts; Added Babel for rollup build; * Added default commonjs package export for Node build; Added automatic contributors list generator for package.json; Co-authored-by: Jay <jasonsaayman@gmail.com>
This commit is contained in:
@@ -0,0 +1,14 @@
|
|||||||
|
module.exports = {
|
||||||
|
"env": {
|
||||||
|
"browser": true,
|
||||||
|
"es2017": true,
|
||||||
|
"node": true
|
||||||
|
},
|
||||||
|
"extends": "eslint:recommended",
|
||||||
|
"parserOptions": {
|
||||||
|
"ecmaVersion": 2017,
|
||||||
|
"sourceType": "module"
|
||||||
|
},
|
||||||
|
"rules": {
|
||||||
|
}
|
||||||
|
}
|
||||||
-151
@@ -1,151 +0,0 @@
|
|||||||
// eslint-disable-next-line strict
|
|
||||||
module.exports = {
|
|
||||||
'globals': {
|
|
||||||
'console': true,
|
|
||||||
'module': true,
|
|
||||||
'require': true
|
|
||||||
},
|
|
||||||
'env': {
|
|
||||||
'browser': true,
|
|
||||||
'node': true
|
|
||||||
},
|
|
||||||
'rules': {
|
|
||||||
/**
|
|
||||||
* Strict mode
|
|
||||||
*/
|
|
||||||
'strict': [2, 'global'], // http://eslint.org/docs/rules/strict
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Variables
|
|
||||||
*/
|
|
||||||
'no-shadow': 2, // http://eslint.org/docs/rules/no-shadow
|
|
||||||
'no-shadow-restricted-names': 2, // http://eslint.org/docs/rules/no-shadow-restricted-names
|
|
||||||
'no-unused-vars': [2, { // http://eslint.org/docs/rules/no-unused-vars
|
|
||||||
'vars': 'local',
|
|
||||||
'args': 'after-used'
|
|
||||||
}],
|
|
||||||
'no-use-before-define': 2, // http://eslint.org/docs/rules/no-use-before-define
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Possible errors
|
|
||||||
*/
|
|
||||||
'comma-dangle': [2, 'never'], // http://eslint.org/docs/rules/comma-dangle
|
|
||||||
'no-cond-assign': [2, 'except-parens'], // http://eslint.org/docs/rules/no-cond-assign
|
|
||||||
'no-console': 1, // http://eslint.org/docs/rules/no-console
|
|
||||||
'no-debugger': 1, // http://eslint.org/docs/rules/no-debugger
|
|
||||||
'no-alert': 1, // http://eslint.org/docs/rules/no-alert
|
|
||||||
'no-constant-condition': 1, // http://eslint.org/docs/rules/no-constant-condition
|
|
||||||
'no-dupe-keys': 2, // http://eslint.org/docs/rules/no-dupe-keys
|
|
||||||
'no-duplicate-case': 2, // http://eslint.org/docs/rules/no-duplicate-case
|
|
||||||
'no-empty': 2, // http://eslint.org/docs/rules/no-empty
|
|
||||||
'no-ex-assign': 2, // http://eslint.org/docs/rules/no-ex-assign
|
|
||||||
'no-extra-boolean-cast': 0, // http://eslint.org/docs/rules/no-extra-boolean-cast
|
|
||||||
'no-extra-semi': 2, // http://eslint.org/docs/rules/no-extra-semi
|
|
||||||
'no-func-assign': 2, // http://eslint.org/docs/rules/no-func-assign
|
|
||||||
'no-inner-declarations': 2, // http://eslint.org/docs/rules/no-inner-declarations
|
|
||||||
'no-invalid-regexp': 2, // http://eslint.org/docs/rules/no-invalid-regexp
|
|
||||||
'no-irregular-whitespace': 2, // http://eslint.org/docs/rules/no-irregular-whitespace
|
|
||||||
'no-obj-calls': 2, // http://eslint.org/docs/rules/no-obj-calls
|
|
||||||
'no-sparse-arrays': 2, // http://eslint.org/docs/rules/no-sparse-arrays
|
|
||||||
'no-unreachable': 2, // http://eslint.org/docs/rules/no-unreachable
|
|
||||||
'use-isnan': 2, // http://eslint.org/docs/rules/use-isnan
|
|
||||||
'block-scoped-var': 2, // http://eslint.org/docs/rules/block-scoped-var
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Best practices
|
|
||||||
*/
|
|
||||||
'consistent-return': 0, // http://eslint.org/docs/rules/consistent-return
|
|
||||||
'curly': [2, 'multi-line'], // http://eslint.org/docs/rules/curly
|
|
||||||
'default-case': 2, // http://eslint.org/docs/rules/default-case
|
|
||||||
'dot-notation': [2, { // http://eslint.org/docs/rules/dot-notation
|
|
||||||
'allowKeywords': true
|
|
||||||
}],
|
|
||||||
'eqeqeq': [2, "smart"], // http://eslint.org/docs/rules/eqeqeq
|
|
||||||
'guard-for-in': 2, // http://eslint.org/docs/rules/guard-for-in
|
|
||||||
'no-caller': 2, // http://eslint.org/docs/rules/no-caller
|
|
||||||
'no-else-return': 2, // http://eslint.org/docs/rules/no-else-return
|
|
||||||
'no-eq-null': 0, // http://eslint.org/docs/rules/no-eq-null
|
|
||||||
'no-eval': 2, // http://eslint.org/docs/rules/no-eval
|
|
||||||
'no-extend-native': 2, // http://eslint.org/docs/rules/no-extend-native
|
|
||||||
'no-extra-bind': 2, // http://eslint.org/docs/rules/no-extra-bind
|
|
||||||
'no-fallthrough': 2, // http://eslint.org/docs/rules/no-fallthrough
|
|
||||||
'no-floating-decimal': 2, // http://eslint.org/docs/rules/no-floating-decimal
|
|
||||||
'no-implied-eval': 2, // http://eslint.org/docs/rules/no-implied-eval
|
|
||||||
'no-lone-blocks': 2, // http://eslint.org/docs/rules/no-lone-blocks
|
|
||||||
'no-loop-func': 2, // http://eslint.org/docs/rules/no-loop-func
|
|
||||||
'no-multi-str': 2, // http://eslint.org/docs/rules/no-multi-str
|
|
||||||
'no-native-reassign': 2, // http://eslint.org/docs/rules/no-native-reassign
|
|
||||||
'no-new': 2, // http://eslint.org/docs/rules/no-new
|
|
||||||
'no-new-func': 2, // http://eslint.org/docs/rules/no-new-func
|
|
||||||
'no-new-wrappers': 2, // http://eslint.org/docs/rules/no-new-wrappers
|
|
||||||
'no-octal': 2, // http://eslint.org/docs/rules/no-octal
|
|
||||||
'no-octal-escape': 2, // http://eslint.org/docs/rules/no-octal-escape
|
|
||||||
'no-param-reassign': 0, // http://eslint.org/docs/rules/no-param-reassign
|
|
||||||
'no-proto': 2, // http://eslint.org/docs/rules/no-proto
|
|
||||||
'no-redeclare': 2, // http://eslint.org/docs/rules/no-redeclare
|
|
||||||
'no-return-assign': 2, // http://eslint.org/docs/rules/no-return-assign
|
|
||||||
'no-script-url': 2, // http://eslint.org/docs/rules/no-script-url
|
|
||||||
'no-self-compare': 2, // http://eslint.org/docs/rules/no-self-compare
|
|
||||||
'no-sequences': 2, // http://eslint.org/docs/rules/no-sequences
|
|
||||||
'no-throw-literal': 2, // http://eslint.org/docs/rules/no-throw-literal
|
|
||||||
'no-with': 2, // http://eslint.org/docs/rules/no-with
|
|
||||||
'radix': 2, // http://eslint.org/docs/rules/radix
|
|
||||||
'vars-on-top': 0, // http://eslint.org/docs/rules/vars-on-top
|
|
||||||
'wrap-iife': [2, 'any'], // http://eslint.org/docs/rules/wrap-iife
|
|
||||||
'yoda': 2, // http://eslint.org/docs/rules/yoda
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Style
|
|
||||||
*/
|
|
||||||
'indent': [2, 2], // http://eslint.org/docs/rules/indent
|
|
||||||
'brace-style': [2, // http://eslint.org/docs/rules/brace-style
|
|
||||||
'1tbs', {
|
|
||||||
'allowSingleLine': true
|
|
||||||
}],
|
|
||||||
'quotes': [
|
|
||||||
2, 'single', 'avoid-escape' // http://eslint.org/docs/rules/quotes
|
|
||||||
],
|
|
||||||
'camelcase': [2, { // http://eslint.org/docs/rules/camelcase
|
|
||||||
'properties': 'never'
|
|
||||||
}],
|
|
||||||
'comma-spacing': [2, { // http://eslint.org/docs/rules/comma-spacing
|
|
||||||
'before': false,
|
|
||||||
'after': true
|
|
||||||
}],
|
|
||||||
'comma-style': [2, 'last'], // http://eslint.org/docs/rules/comma-style
|
|
||||||
'eol-last': 2, // http://eslint.org/docs/rules/eol-last
|
|
||||||
'func-names': 0, // http://eslint.org/docs/rules/func-names
|
|
||||||
'key-spacing': [2, { // http://eslint.org/docs/rules/key-spacing
|
|
||||||
'beforeColon': false,
|
|
||||||
'afterColon': true
|
|
||||||
}],
|
|
||||||
'new-cap': [2, { // http://eslint.org/docs/rules/new-cap
|
|
||||||
'newIsCap': true
|
|
||||||
}],
|
|
||||||
'no-multiple-empty-lines': [2, { // http://eslint.org/docs/rules/no-multiple-empty-lines
|
|
||||||
'max': 2
|
|
||||||
}],
|
|
||||||
'no-nested-ternary': 2, // http://eslint.org/docs/rules/no-nested-ternary
|
|
||||||
'no-new-object': 2, // http://eslint.org/docs/rules/no-new-object
|
|
||||||
'no-spaced-func': 2, // http://eslint.org/docs/rules/no-spaced-func
|
|
||||||
'no-trailing-spaces': 2, // http://eslint.org/docs/rules/no-trailing-spaces
|
|
||||||
'no-extra-parens': [2, 'functions'], // http://eslint.org/docs/rules/no-extra-parens
|
|
||||||
'no-underscore-dangle': 0, // http://eslint.org/docs/rules/no-underscore-dangle
|
|
||||||
'one-var': [2, 'never'], // http://eslint.org/docs/rules/one-var
|
|
||||||
'padded-blocks': [2, 'never'], // http://eslint.org/docs/rules/padded-blocks
|
|
||||||
'semi': [2, 'always'], // http://eslint.org/docs/rules/semi
|
|
||||||
'semi-spacing': [2, { // http://eslint.org/docs/rules/semi-spacing
|
|
||||||
'before': false,
|
|
||||||
'after': true
|
|
||||||
}],
|
|
||||||
'keyword-spacing': 2, // http://eslint.org/docs/rules/keyword-spacing
|
|
||||||
'space-before-blocks': 2, // http://eslint.org/docs/rules/space-before-blocks
|
|
||||||
'space-before-function-paren': [2, 'never'], // http://eslint.org/docs/rules/space-before-function-paren
|
|
||||||
'space-infix-ops': 2, // http://eslint.org/docs/rules/space-infix-ops
|
|
||||||
'spaced-comment': [2, 'always', {// http://eslint.org/docs/rules/spaced-comment
|
|
||||||
'markers': ['global', 'eslint']
|
|
||||||
}]
|
|
||||||
},
|
|
||||||
|
|
||||||
'ignorePatterns': ['**/env/data.js']
|
|
||||||
};
|
|
||||||
-101
@@ -1,101 +0,0 @@
|
|||||||
// eslint-disable-next-line strict
|
|
||||||
module.exports = function(grunt) {
|
|
||||||
require('load-grunt-tasks')(grunt);
|
|
||||||
|
|
||||||
grunt.initConfig({
|
|
||||||
pkg: grunt.file.readJSON('package.json'),
|
|
||||||
meta: {
|
|
||||||
banner: '/* <%= pkg.name %> v<%= pkg.version %> | (c) <%= grunt.template.today("yyyy") %> by Matt Zabriskie */\n'
|
|
||||||
},
|
|
||||||
|
|
||||||
clean: {
|
|
||||||
dist: 'dist/**'
|
|
||||||
},
|
|
||||||
|
|
||||||
package2bower: {
|
|
||||||
all: {
|
|
||||||
fields: [
|
|
||||||
'name',
|
|
||||||
'description',
|
|
||||||
'version',
|
|
||||||
'homepage',
|
|
||||||
'license',
|
|
||||||
'keywords'
|
|
||||||
]
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
package2env: {
|
|
||||||
all: {}
|
|
||||||
},
|
|
||||||
|
|
||||||
eslint: {
|
|
||||||
target: ['lib/**/*.js']
|
|
||||||
},
|
|
||||||
|
|
||||||
karma: {
|
|
||||||
options: {
|
|
||||||
configFile: 'karma.conf.js'
|
|
||||||
},
|
|
||||||
single: {
|
|
||||||
singleRun: true
|
|
||||||
},
|
|
||||||
continuous: {
|
|
||||||
singleRun: false
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
mochaTest: {
|
|
||||||
test: {
|
|
||||||
src: ['test/unit/**/*.js']
|
|
||||||
},
|
|
||||||
options: {
|
|
||||||
timeout: 30000
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
watch: {
|
|
||||||
build: {
|
|
||||||
files: ['lib/**/*.js'],
|
|
||||||
tasks: ['build']
|
|
||||||
},
|
|
||||||
test: {
|
|
||||||
files: ['lib/**/*.js', 'test/**/*.js', '!test/typescript/axios.js', '!test/typescript/out.js'],
|
|
||||||
tasks: ['test']
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
shell: {
|
|
||||||
rollup: {
|
|
||||||
command: 'rollup -c -m'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
grunt.registerMultiTask('package2bower', 'Sync package.json to bower.json', function() {
|
|
||||||
var npm = grunt.file.readJSON('package.json');
|
|
||||||
var bower = grunt.file.readJSON('bower.json');
|
|
||||||
var fields = this.data.fields || [];
|
|
||||||
|
|
||||||
for (var i = 0, l = fields.length; i < l; i++) {
|
|
||||||
var field = fields[i];
|
|
||||||
bower[field] = npm[field];
|
|
||||||
}
|
|
||||||
|
|
||||||
grunt.file.write('bower.json', JSON.stringify(bower, null, 2));
|
|
||||||
});
|
|
||||||
|
|
||||||
grunt.registerMultiTask('package2env', 'Sync package.json to env.json', function() {
|
|
||||||
var npm = grunt.file.readJSON('package.json');
|
|
||||||
grunt.file.write('./lib/env/data.js', [
|
|
||||||
'module.exports = ',
|
|
||||||
JSON.stringify({
|
|
||||||
version: npm.version
|
|
||||||
}, null, 2),
|
|
||||||
';'].join(''));
|
|
||||||
});
|
|
||||||
|
|
||||||
grunt.registerTask('test', 'Run the jasmine and mocha tests', ['eslint', 'mochaTest', 'karma:single']);
|
|
||||||
grunt.registerTask('build', 'Run rollup and bundle the source', ['clean', 'shell:rollup']);
|
|
||||||
grunt.registerTask('version', 'Sync version info for a release', ['package2bower', 'package2env']);
|
|
||||||
};
|
|
||||||
@@ -47,7 +47,7 @@ Promise based HTTP client for the browser and node.js
|
|||||||
- [FormData](#formdata)
|
- [FormData](#formdata)
|
||||||
- [🆕 Automatic serialization](#-automatic-serialization-to-formdata)
|
- [🆕 Automatic serialization](#-automatic-serialization-to-formdata)
|
||||||
- [Files Posting](#files-posting)
|
- [Files Posting](#files-posting)
|
||||||
- [HTML Form Posting](#html-form-posting-browser)
|
- [HTML Form Posting](#-html-form-posting-browser)
|
||||||
- [Semver](#semver)
|
- [Semver](#semver)
|
||||||
- [Promises](#promises)
|
- [Promises](#promises)
|
||||||
- [TypeScript](#typescript)
|
- [TypeScript](#typescript)
|
||||||
|
|||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
const {spawn} = require('child_process');
|
import {spawn} from 'child_process';
|
||||||
|
|
||||||
const args = process.argv.slice(2);
|
const args = process.argv.slice(2);
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
var people = [
|
const people = [
|
||||||
{
|
{
|
||||||
"name": "Matt Zabriskie",
|
"name": "Matt Zabriskie",
|
||||||
"github": "mzabriskie",
|
"github": "mzabriskie",
|
||||||
@@ -25,7 +25,7 @@ var people = [
|
|||||||
}
|
}
|
||||||
];
|
];
|
||||||
|
|
||||||
module.exports = function (req, res) {
|
export default function (req, res) {
|
||||||
res.writeHead(200, {
|
res.writeHead(200, {
|
||||||
'Content-Type': 'text/json'
|
'Content-Type': 'text/json'
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
module.exports = function (req, res) {
|
export default function (req, res) {
|
||||||
var data = '';
|
let data = '';
|
||||||
|
|
||||||
req.on('data', function (chunk) {
|
req.on('data', function (chunk) {
|
||||||
data += chunk;
|
data += chunk;
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
module.exports = function (req, res) {
|
export default function (req, res) {
|
||||||
|
|
||||||
req.on('data', function (chunk) {
|
req.on('data', function (chunk) {
|
||||||
});
|
});
|
||||||
|
|||||||
+21
-16
@@ -1,18 +1,23 @@
|
|||||||
var fs = require('fs');
|
import fs from 'fs';
|
||||||
var path = require('path');
|
import path from 'path';
|
||||||
var http = require('http');
|
import http from 'http';
|
||||||
var argv = require('minimist')(process.argv.slice(2));
|
import minimist from 'minimist';
|
||||||
var server;
|
import url from "url";
|
||||||
var dirs;
|
const argv = minimist(process.argv.slice(2));
|
||||||
|
let server;
|
||||||
|
let dirs;
|
||||||
|
|
||||||
|
const __filename = url.fileURLToPath(import.meta.url);
|
||||||
|
const __dirname = path.dirname(__filename);
|
||||||
|
|
||||||
function listDirs(root) {
|
function listDirs(root) {
|
||||||
var files = fs.readdirSync(root);
|
const files = fs.readdirSync(root);
|
||||||
var dirs = [];
|
const dirs = [];
|
||||||
|
|
||||||
for (var i = 0, l = files.length; i < l; i++) {
|
for (let i = 0, l = files.length; i < l; i++) {
|
||||||
var file = files[i];
|
const file = files[i];
|
||||||
if (file[0] !== '.') {
|
if (file[0] !== '.') {
|
||||||
var stat = fs.statSync(path.join(root, file));
|
const stat = fs.statSync(path.join(root, file));
|
||||||
if (stat.isDirectory()) {
|
if (stat.isDirectory()) {
|
||||||
dirs.push(file);
|
dirs.push(file);
|
||||||
}
|
}
|
||||||
@@ -23,8 +28,8 @@ function listDirs(root) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function getIndexTemplate() {
|
function getIndexTemplate() {
|
||||||
var links = dirs.map(function (dir) {
|
const links = dirs.map(function (dir) {
|
||||||
var url = '/' + dir;
|
const url = '/' + dir;
|
||||||
return '<li onclick="document.location=\'' + url + '\'"><a href="' + url + '">' + url + '</a></li>';
|
return '<li onclick="document.location=\'' + url + '\'"><a href="' + url + '">' + url + '</a></li>';
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -74,7 +79,7 @@ function pipeFileToResponse(res, file, type) {
|
|||||||
dirs = listDirs(__dirname);
|
dirs = listDirs(__dirname);
|
||||||
|
|
||||||
server = http.createServer(function (req, res) {
|
server = http.createServer(function (req, res) {
|
||||||
var url = req.url;
|
let url = req.url;
|
||||||
|
|
||||||
// Process axios itself
|
// Process axios itself
|
||||||
if (/axios\.min\.js$/.test(url)) {
|
if (/axios\.min\.js$/.test(url)) {
|
||||||
@@ -106,7 +111,7 @@ server = http.createServer(function (req, res) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Format request /get -> /get/index.html
|
// Format request /get -> /get/index.html
|
||||||
var parts = url.split('/');
|
const parts = url.split('/');
|
||||||
if (dirs.indexOf(parts[parts.length - 1]) > -1) {
|
if (dirs.indexOf(parts[parts.length - 1]) > -1) {
|
||||||
url += '/index.html';
|
url += '/index.html';
|
||||||
}
|
}
|
||||||
@@ -136,5 +141,5 @@ server = http.createServer(function (req, res) {
|
|||||||
const PORT = argv.p || 3000;
|
const PORT = argv.p || 3000;
|
||||||
|
|
||||||
server.listen(PORT, () => {
|
server.listen(PORT, () => {
|
||||||
console.log(`Examples running on ${PORT}`);
|
console.log(`Examples running on ${PORT}`);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
module.exports = function (req, res) {
|
export default function (req, res) {
|
||||||
var data = '';
|
let data = '';
|
||||||
|
|
||||||
req.on('data', function (chunk) {
|
req.on('data', function (chunk) {
|
||||||
data += chunk;
|
data += chunk;
|
||||||
|
|||||||
+87
@@ -0,0 +1,87 @@
|
|||||||
|
import gulp from 'gulp';
|
||||||
|
import fs from 'fs-extra';
|
||||||
|
import axios from './index.js';
|
||||||
|
|
||||||
|
gulp.task('default', async function(){
|
||||||
|
console.log('hello!');
|
||||||
|
});
|
||||||
|
|
||||||
|
const clear = gulp.task('clear', async function() {
|
||||||
|
await fs.emptyDir('./dist/')
|
||||||
|
});
|
||||||
|
|
||||||
|
const bower = gulp.task('bower', async function () {
|
||||||
|
const npm = JSON.parse(await fs.readFile('package.json'));
|
||||||
|
const bower = JSON.parse(await fs.readFile('bower.json'));
|
||||||
|
|
||||||
|
const fields = [
|
||||||
|
'name',
|
||||||
|
'description',
|
||||||
|
'version',
|
||||||
|
'homepage',
|
||||||
|
'license',
|
||||||
|
'keywords'
|
||||||
|
];
|
||||||
|
|
||||||
|
for (let i = 0, l = fields.length; i < l; i++) {
|
||||||
|
const field = fields[i];
|
||||||
|
bower[field] = npm[field];
|
||||||
|
}
|
||||||
|
|
||||||
|
await fs.writeFile('bower.json', JSON.stringify(bower, null, 2));
|
||||||
|
});
|
||||||
|
|
||||||
|
async function getContributors(user, repo, maxCount = 1) {
|
||||||
|
const contributors = (await axios.get(
|
||||||
|
`https://api.github.com/repos/${encodeURIComponent(user)}/${encodeURIComponent(repo)}/contributors?per_page=${maxCount}`
|
||||||
|
)).data;
|
||||||
|
|
||||||
|
return Promise.all(contributors.map(async (contributor)=> {
|
||||||
|
return {...contributor, ...(await axios.get(
|
||||||
|
`https://api.github.com/users/${encodeURIComponent(contributor.login)}`
|
||||||
|
)).data};
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
const packageJSON = gulp.task('package', async function () {
|
||||||
|
const CONTRIBUTION_THRESHOLD = 3;
|
||||||
|
|
||||||
|
const npm = JSON.parse(await fs.readFile('package.json'));
|
||||||
|
|
||||||
|
try {
|
||||||
|
const contributors = await getContributors('axios', 'axios', 15);
|
||||||
|
|
||||||
|
npm.contributors = contributors
|
||||||
|
.filter(
|
||||||
|
({type, contributions}) => type.toLowerCase() === 'user' && contributions >= CONTRIBUTION_THRESHOLD
|
||||||
|
)
|
||||||
|
.map(({login, name, url}) => `${name || login} (https://github.com/${login})`);
|
||||||
|
|
||||||
|
await fs.writeFile('package.json', JSON.stringify(npm, null, 2));
|
||||||
|
} catch (err) {
|
||||||
|
if (axios.isAxiosError(err) && err.response && err.response.status === 403) {
|
||||||
|
throw Error(`GitHub API Error: ${err.response.data && err.response.data.message}`);
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const env = gulp.task('env', async function () {
|
||||||
|
var npm = JSON.parse(await fs.readFile('package.json'));
|
||||||
|
|
||||||
|
await fs.writeFile('./lib/env/data.js', Object.entries({
|
||||||
|
VERSION: npm.version
|
||||||
|
}).map(([key, value]) => {
|
||||||
|
return `export const ${key} = ${JSON.stringify(value)};`
|
||||||
|
}).join('\n'));
|
||||||
|
});
|
||||||
|
|
||||||
|
const version = gulp.series('bower', 'env', 'package');
|
||||||
|
|
||||||
|
export {
|
||||||
|
bower,
|
||||||
|
env,
|
||||||
|
clear,
|
||||||
|
version,
|
||||||
|
packageJSON
|
||||||
|
}
|
||||||
Vendored
+134
-57
@@ -1,5 +1,6 @@
|
|||||||
// TypeScript Version: 4.1
|
// TypeScript Version: 4.1
|
||||||
type AxiosHeaders = Record<string, string | string[] | number | boolean>;
|
type AxiosHeaderValue = string | string[] | number | boolean | null;
|
||||||
|
type RawAxiosHeaders = Record<string, AxiosHeaderValue>;
|
||||||
|
|
||||||
type MethodsHeaders = {
|
type MethodsHeaders = {
|
||||||
[Key in Method as Lowercase<Key>]: AxiosHeaders;
|
[Key in Method as Lowercase<Key>]: AxiosHeaders;
|
||||||
@@ -9,18 +10,78 @@ interface CommonHeaders {
|
|||||||
common: AxiosHeaders;
|
common: AxiosHeaders;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AxiosRequestHeaders = Partial<AxiosHeaders & MethodsHeaders & CommonHeaders>;
|
type AxiosHeaderMatcher = (this: AxiosHeaders, value: string, name: string, headers: RawAxiosHeaders) => boolean;
|
||||||
|
|
||||||
export type AxiosResponseHeaders = Record<string, string> & {
|
type AxiosHeaderSetter = (value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher) => AxiosHeaders;
|
||||||
|
|
||||||
|
type AxiosHeaderGetter = ((parser?: RegExp) => RegExpExecArray | null) |
|
||||||
|
((matcher?: AxiosHeaderMatcher) => AxiosHeaderValue);
|
||||||
|
|
||||||
|
type AxiosHeaderTester = (matcher?: AxiosHeaderMatcher) => boolean;
|
||||||
|
|
||||||
|
export class AxiosHeaders {
|
||||||
|
constructor(
|
||||||
|
headers?: RawAxiosHeaders | AxiosHeaders,
|
||||||
|
defaultHeaders?: RawAxiosHeaders | AxiosHeaders
|
||||||
|
);
|
||||||
|
|
||||||
|
set(headerName?: string, value?: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
|
||||||
|
set(headers?: RawAxiosHeaders | AxiosHeaders, rewrite?: boolean): AxiosHeaders;
|
||||||
|
|
||||||
|
get(headerName: string, parser: RegExp): RegExpExecArray | null;
|
||||||
|
get(headerName: string, matcher?: true | AxiosHeaderMatcher): AxiosHeaderValue;
|
||||||
|
|
||||||
|
has(header: string, matcher?: true | AxiosHeaderMatcher): boolean;
|
||||||
|
|
||||||
|
delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean;
|
||||||
|
|
||||||
|
clear(): boolean;
|
||||||
|
|
||||||
|
normalize(format: boolean): AxiosHeaders;
|
||||||
|
|
||||||
|
toJSON(): RawAxiosHeaders;
|
||||||
|
|
||||||
|
static from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders;
|
||||||
|
|
||||||
|
static accessor(header: string | string[]): AxiosHeaders;
|
||||||
|
|
||||||
|
setContentType: AxiosHeaderSetter;
|
||||||
|
getContentType: AxiosHeaderGetter;
|
||||||
|
hasContentType: AxiosHeaderTester;
|
||||||
|
|
||||||
|
setContentLength: AxiosHeaderSetter;
|
||||||
|
getContentLength: AxiosHeaderGetter;
|
||||||
|
hasContentLength: AxiosHeaderTester;
|
||||||
|
|
||||||
|
setAccept: AxiosHeaderSetter;
|
||||||
|
getAccept: AxiosHeaderGetter;
|
||||||
|
hasAccept: AxiosHeaderTester;
|
||||||
|
|
||||||
|
setUserAgent: AxiosHeaderSetter;
|
||||||
|
getUserAgent: AxiosHeaderGetter;
|
||||||
|
hasUserAgent: AxiosHeaderTester;
|
||||||
|
|
||||||
|
setContentEncoding: AxiosHeaderSetter;
|
||||||
|
getContentEncoding: AxiosHeaderGetter;
|
||||||
|
hasContentEncoding: AxiosHeaderTester;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type RawAxiosRequestHeaders = Partial<RawAxiosHeaders & MethodsHeaders & CommonHeaders>;
|
||||||
|
|
||||||
|
export type AxiosRequestHeaders = Partial<RawAxiosHeaders & MethodsHeaders & CommonHeaders> & AxiosHeaders;
|
||||||
|
|
||||||
|
export type RawAxiosResponseHeaders = Partial<Record<string, string> & {
|
||||||
"set-cookie"?: string[]
|
"set-cookie"?: string[]
|
||||||
};
|
}>;
|
||||||
|
|
||||||
|
export type AxiosResponseHeaders = RawAxiosResponseHeaders & AxiosHeaders;
|
||||||
|
|
||||||
export interface AxiosRequestTransformer {
|
export interface AxiosRequestTransformer {
|
||||||
(data: any, headers: AxiosRequestHeaders): any;
|
(this: AxiosRequestConfig, data: any, headers: AxiosRequestHeaders): any;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AxiosResponseTransformer {
|
export interface AxiosResponseTransformer {
|
||||||
(data: any, headers?: AxiosResponseHeaders, status?: number): any;
|
(this: AxiosRequestConfig, data: any, headers: AxiosResponseHeaders, status?: number): any;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AxiosAdapter {
|
export interface AxiosAdapter {
|
||||||
@@ -43,38 +104,38 @@ export interface AxiosProxyConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export type Method =
|
export type Method =
|
||||||
| 'get' | 'GET'
|
| 'get' | 'GET'
|
||||||
| 'delete' | 'DELETE'
|
| 'delete' | 'DELETE'
|
||||||
| 'head' | 'HEAD'
|
| 'head' | 'HEAD'
|
||||||
| 'options' | 'OPTIONS'
|
| 'options' | 'OPTIONS'
|
||||||
| 'post' | 'POST'
|
| 'post' | 'POST'
|
||||||
| 'put' | 'PUT'
|
| 'put' | 'PUT'
|
||||||
| 'patch' | 'PATCH'
|
| 'patch' | 'PATCH'
|
||||||
| 'purge' | 'PURGE'
|
| 'purge' | 'PURGE'
|
||||||
| 'link' | 'LINK'
|
| 'link' | 'LINK'
|
||||||
| 'unlink' | 'UNLINK';
|
| 'unlink' | 'UNLINK';
|
||||||
|
|
||||||
export type ResponseType =
|
export type ResponseType =
|
||||||
| 'arraybuffer'
|
| 'arraybuffer'
|
||||||
| 'blob'
|
| 'blob'
|
||||||
| 'document'
|
| 'document'
|
||||||
| 'json'
|
| 'json'
|
||||||
| 'text'
|
| 'text'
|
||||||
| 'stream';
|
| 'stream';
|
||||||
|
|
||||||
export type responseEncoding =
|
export type responseEncoding =
|
||||||
| 'ascii' | 'ASCII'
|
| 'ascii' | 'ASCII'
|
||||||
| 'ansi' | 'ANSI'
|
| 'ansi' | 'ANSI'
|
||||||
| 'binary' | 'BINARY'
|
| 'binary' | 'BINARY'
|
||||||
| 'base64' | 'BASE64'
|
| 'base64' | 'BASE64'
|
||||||
| 'base64url' | 'BASE64URL'
|
| 'base64url' | 'BASE64URL'
|
||||||
| 'hex' | 'HEX'
|
| 'hex' | 'HEX'
|
||||||
| 'latin1' | 'LATIN1'
|
| 'latin1' | 'LATIN1'
|
||||||
| 'ucs-2' | 'UCS-2'
|
| 'ucs-2' | 'UCS-2'
|
||||||
| 'ucs2' | 'UCS2'
|
| 'ucs2' | 'UCS2'
|
||||||
| 'utf-8' | 'UTF-8'
|
| 'utf-8' | 'UTF-8'
|
||||||
| 'utf8' | 'UTF8'
|
| 'utf8' | 'UTF8'
|
||||||
| 'utf16le' | 'UTF16LE';
|
| 'utf16le' | 'UTF16LE';
|
||||||
|
|
||||||
export interface TransitionalOptions {
|
export interface TransitionalOptions {
|
||||||
silentJSONParsing?: boolean;
|
silentJSONParsing?: boolean;
|
||||||
@@ -124,13 +185,28 @@ export interface ParamsSerializerOptions extends SerializerOptions {
|
|||||||
encode?: ParamEncoder;
|
encode?: ParamEncoder;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type MaxUploadRate = number;
|
||||||
|
|
||||||
|
type MaxDownloadRate = number;
|
||||||
|
|
||||||
|
export interface AxiosProgressEvent {
|
||||||
|
loaded: number;
|
||||||
|
total?: number;
|
||||||
|
progress?: number;
|
||||||
|
bytes: number;
|
||||||
|
rate?: number;
|
||||||
|
estimated?: number;
|
||||||
|
upload?: boolean;
|
||||||
|
download?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
export interface AxiosRequestConfig<D = any> {
|
export interface AxiosRequestConfig<D = any> {
|
||||||
url?: string;
|
url?: string;
|
||||||
method?: Method | string;
|
method?: Method | string;
|
||||||
baseURL?: string;
|
baseURL?: string;
|
||||||
transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];
|
transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];
|
||||||
transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];
|
transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];
|
||||||
headers?: AxiosRequestHeaders;
|
headers?: RawAxiosRequestHeaders;
|
||||||
params?: any;
|
params?: any;
|
||||||
paramsSerializer?: ParamsSerializerOptions;
|
paramsSerializer?: ParamsSerializerOptions;
|
||||||
data?: D;
|
data?: D;
|
||||||
@@ -143,12 +219,13 @@ export interface AxiosRequestConfig<D = any> {
|
|||||||
responseEncoding?: responseEncoding | string;
|
responseEncoding?: responseEncoding | string;
|
||||||
xsrfCookieName?: string;
|
xsrfCookieName?: string;
|
||||||
xsrfHeaderName?: string;
|
xsrfHeaderName?: string;
|
||||||
onUploadProgress?: (progressEvent: ProgressEvent) => void;
|
onUploadProgress?: (progressEvent: AxiosProgressEvent) => void;
|
||||||
onDownloadProgress?: (progressEvent: ProgressEvent) => void;
|
onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void;
|
||||||
maxContentLength?: number;
|
maxContentLength?: number;
|
||||||
validateStatus?: ((status: number) => boolean) | null;
|
validateStatus?: ((status: number) => boolean) | null;
|
||||||
maxBodyLength?: number;
|
maxBodyLength?: number;
|
||||||
maxRedirects?: number;
|
maxRedirects?: number;
|
||||||
|
maxRate?: number | [MaxUploadRate, MaxDownloadRate];
|
||||||
beforeRedirect?: (options: Record<string, any>, responseDetails: {headers: Record<string, string>}) => void;
|
beforeRedirect?: (options: Record<string, any>, responseDetails: {headers: Record<string, string>}) => void;
|
||||||
socketPath?: string | null;
|
socketPath?: string | null;
|
||||||
httpAgent?: any;
|
httpAgent?: any;
|
||||||
@@ -166,17 +243,17 @@ export interface AxiosRequestConfig<D = any> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface HeadersDefaults {
|
export interface HeadersDefaults {
|
||||||
common: AxiosRequestHeaders;
|
common: RawAxiosRequestHeaders;
|
||||||
delete: AxiosRequestHeaders;
|
delete: RawAxiosRequestHeaders;
|
||||||
get: AxiosRequestHeaders;
|
get: RawAxiosRequestHeaders;
|
||||||
head: AxiosRequestHeaders;
|
head: RawAxiosRequestHeaders;
|
||||||
post: AxiosRequestHeaders;
|
post: RawAxiosRequestHeaders;
|
||||||
put: AxiosRequestHeaders;
|
put: RawAxiosRequestHeaders;
|
||||||
patch: AxiosRequestHeaders;
|
patch: RawAxiosRequestHeaders;
|
||||||
options?: AxiosRequestHeaders;
|
options?: RawAxiosRequestHeaders;
|
||||||
purge?: AxiosRequestHeaders;
|
purge?: RawAxiosRequestHeaders;
|
||||||
link?: AxiosRequestHeaders;
|
link?: RawAxiosRequestHeaders;
|
||||||
unlink?: AxiosRequestHeaders;
|
unlink?: RawAxiosRequestHeaders;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AxiosDefaults<D = any> extends Omit<AxiosRequestConfig<D>, 'headers'> {
|
export interface AxiosDefaults<D = any> extends Omit<AxiosRequestConfig<D>, 'headers'> {
|
||||||
@@ -184,25 +261,25 @@ export interface AxiosDefaults<D = any> extends Omit<AxiosRequestConfig<D>, 'hea
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface CreateAxiosDefaults<D = any> extends Omit<AxiosRequestConfig<D>, 'headers'> {
|
export interface CreateAxiosDefaults<D = any> extends Omit<AxiosRequestConfig<D>, 'headers'> {
|
||||||
headers?: AxiosRequestHeaders | Partial<HeadersDefaults>;
|
headers?: RawAxiosRequestHeaders | Partial<HeadersDefaults>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AxiosResponse<T = any, D = any> {
|
export interface AxiosResponse<T = any, D = any> {
|
||||||
data: T;
|
data: T;
|
||||||
status: number;
|
status: number;
|
||||||
statusText: string;
|
statusText: string;
|
||||||
headers: AxiosResponseHeaders;
|
headers: RawAxiosResponseHeaders | AxiosResponseHeaders;
|
||||||
config: AxiosRequestConfig<D>;
|
config: AxiosRequestConfig<D>;
|
||||||
request?: any;
|
request?: any;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class AxiosError<T = unknown, D = any> extends Error {
|
export class AxiosError<T = unknown, D = any> extends Error {
|
||||||
constructor(
|
constructor(
|
||||||
message?: string,
|
message?: string,
|
||||||
code?: string,
|
code?: string,
|
||||||
config?: AxiosRequestConfig<D>,
|
config?: AxiosRequestConfig<D>,
|
||||||
request?: any,
|
request?: any,
|
||||||
response?: AxiosResponse<T, D>
|
response?: AxiosResponse<T, D>
|
||||||
);
|
);
|
||||||
|
|
||||||
config?: AxiosRequestConfig<D>;
|
config?: AxiosRequestConfig<D>;
|
||||||
@@ -297,7 +374,7 @@ export interface AxiosInstance extends Axios {
|
|||||||
|
|
||||||
defaults: Omit<AxiosDefaults, 'headers'> & {
|
defaults: Omit<AxiosDefaults, 'headers'> & {
|
||||||
headers: HeadersDefaults & {
|
headers: HeadersDefaults & {
|
||||||
[key: string]: string | number | boolean | undefined
|
[key: string]: AxiosHeaderValue
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1 +1,2 @@
|
|||||||
module.exports = require('./lib/axios');
|
import axios from './lib/axios.js';
|
||||||
|
export default axios;
|
||||||
|
|||||||
@@ -6,7 +6,8 @@
|
|||||||
|
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var webpack = require('webpack');
|
var resolve = require('@rollup/plugin-node-resolve').default;
|
||||||
|
var commonjs = require('@rollup/plugin-commonjs');
|
||||||
|
|
||||||
function createCustomLauncher(browser, version, platform) {
|
function createCustomLauncher(browser, version, platform) {
|
||||||
return {
|
return {
|
||||||
@@ -19,7 +20,7 @@ function createCustomLauncher(browser, version, platform) {
|
|||||||
|
|
||||||
module.exports = function(config) {
|
module.exports = function(config) {
|
||||||
var customLaunchers = {};
|
var customLaunchers = {};
|
||||||
var browsers = [];
|
var browsers = process.env.Browsers && process.env.Browsers.split(',');
|
||||||
var sauceLabs;
|
var sauceLabs;
|
||||||
|
|
||||||
if (process.env.SAUCE_USERNAME || process.env.SAUCE_ACCESS_KEY) {
|
if (process.env.SAUCE_USERNAME || process.env.SAUCE_ACCESS_KEY) {
|
||||||
@@ -52,7 +53,7 @@ module.exports = function(config) {
|
|||||||
|
|
||||||
// Firefox
|
// Firefox
|
||||||
if (runAll || process.env.SAUCE_FIREFOX) {
|
if (runAll || process.env.SAUCE_FIREFOX) {
|
||||||
customLaunchers.SL_Firefox = createCustomLauncher('firefox');
|
//customLaunchers.SL_Firefox = createCustomLauncher('firefox');
|
||||||
// customLaunchers.SL_FirefoxDev = createCustomLauncher('firefox', 'dev');
|
// customLaunchers.SL_FirefoxDev = createCustomLauncher('firefox', 'dev');
|
||||||
// customLaunchers.SL_FirefoxBeta = createCustomLauncher('firefox', 'beta');
|
// customLaunchers.SL_FirefoxBeta = createCustomLauncher('firefox', 'beta');
|
||||||
}
|
}
|
||||||
@@ -127,12 +128,12 @@ module.exports = function(config) {
|
|||||||
'Running on Travis.'
|
'Running on Travis.'
|
||||||
);
|
);
|
||||||
browsers = ['Firefox'];
|
browsers = ['Firefox'];
|
||||||
} else if (process.env.GITHUB_ACTIONS !== 'false') {
|
} else if (process.env.GITHUB_ACTIONS === 'true') {
|
||||||
console.log('Running ci on Github Actions.');
|
console.log('Running ci on Github Actions.');
|
||||||
browsers = ['FirefoxHeadless', 'ChromeHeadless'];
|
browsers = ['FirefoxHeadless', 'ChromeHeadless'];
|
||||||
} else {
|
} else {
|
||||||
console.log('Running locally since SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables are not set.');
|
browsers = browsers || ['Chrome'];
|
||||||
browsers = ['Firefox', 'Chrome'];
|
console.log(`Running ${browsers} locally since SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables are not set.`);
|
||||||
}
|
}
|
||||||
|
|
||||||
config.set({
|
config.set({
|
||||||
@@ -147,8 +148,8 @@ module.exports = function(config) {
|
|||||||
|
|
||||||
// list of files / patterns to load in the browser
|
// list of files / patterns to load in the browser
|
||||||
files: [
|
files: [
|
||||||
'test/specs/__helpers.js',
|
{pattern: 'test/specs/__helpers.js', watched: false},
|
||||||
'test/specs/**/*.spec.js'
|
{pattern: 'test/specs/**/*.spec.js', watched: false}
|
||||||
],
|
],
|
||||||
|
|
||||||
|
|
||||||
@@ -159,8 +160,20 @@ module.exports = function(config) {
|
|||||||
// preprocess matching files before serving them to the browser
|
// preprocess matching files before serving them to the browser
|
||||||
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
|
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
|
||||||
preprocessors: {
|
preprocessors: {
|
||||||
'test/specs/__helpers.js': ['webpack', 'sourcemap'],
|
'test/specs/__helpers.js': ['rollup'],
|
||||||
'test/specs/**/*.spec.js': ['webpack', 'sourcemap']
|
'test/specs/**/*.spec.js': ['rollup']
|
||||||
|
},
|
||||||
|
|
||||||
|
rollupPreprocessor: {
|
||||||
|
plugins: [
|
||||||
|
resolve({browser: true}),
|
||||||
|
commonjs()
|
||||||
|
],
|
||||||
|
output: {
|
||||||
|
format: 'iife',
|
||||||
|
name: '_axios',
|
||||||
|
sourcemap: 'inline'
|
||||||
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|
||||||
+229
-121
@@ -1,27 +1,33 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var utils = require('./../utils');
|
import utils from './../utils.js';
|
||||||
var settle = require('./../core/settle');
|
import settle from './../core/settle.js';
|
||||||
var buildFullPath = require('../core/buildFullPath');
|
import buildFullPath from '../core/buildFullPath.js';
|
||||||
var buildURL = require('./../helpers/buildURL');
|
import buildURL from './../helpers/buildURL.js';
|
||||||
var getProxyForUrl = require('proxy-from-env').getProxyForUrl;
|
import {getProxyForUrl} from 'proxy-from-env';
|
||||||
var http = require('http');
|
import http from 'http';
|
||||||
var https = require('https');
|
import https from 'https';
|
||||||
var httpFollow = require('follow-redirects/http');
|
import followRedirects from 'follow-redirects';
|
||||||
var httpsFollow = require('follow-redirects/https');
|
import url from 'url';
|
||||||
var url = require('url');
|
import zlib from 'zlib';
|
||||||
var zlib = require('zlib');
|
import {VERSION} from '../env/data.js';
|
||||||
var VERSION = require('./../env/data').version;
|
import transitionalDefaults from '../defaults/transitional.js';
|
||||||
var transitionalDefaults = require('../defaults/transitional');
|
import AxiosError from '../core/AxiosError.js';
|
||||||
var AxiosError = require('../core/AxiosError');
|
import CanceledError from '../cancel/CanceledError.js';
|
||||||
var CanceledError = require('../cancel/CanceledError');
|
import platform from '../platform/index.js';
|
||||||
var platform = require('../platform');
|
import fromDataURI from '../helpers/fromDataURI.js';
|
||||||
var fromDataURI = require('../helpers/fromDataURI');
|
import stream from 'stream';
|
||||||
var stream = require('stream');
|
import AxiosHeaders from '../core/AxiosHeaders.js';
|
||||||
|
import AxiosTransformStream from '../helpers/AxiosTransformStream.js';
|
||||||
|
import EventEmitter from 'events';
|
||||||
|
|
||||||
var isHttps = /https:?/;
|
const isBrotliSupported = utils.isFunction(zlib.createBrotliDecompress);
|
||||||
|
|
||||||
var supportedProtocols = platform.protocols.map(function(protocol) {
|
const {http: httpFollow, https: httpsFollow} = followRedirects;
|
||||||
|
|
||||||
|
const isHttps = /https:?/;
|
||||||
|
|
||||||
|
const supportedProtocols = platform.protocols.map(protocol => {
|
||||||
return protocol + ':';
|
return protocol + ':';
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -52,9 +58,9 @@ function dispatchBeforeRedirect(options) {
|
|||||||
* @returns {http.ClientRequestArgs}
|
* @returns {http.ClientRequestArgs}
|
||||||
*/
|
*/
|
||||||
function setProxy(options, configProxy, location) {
|
function setProxy(options, configProxy, location) {
|
||||||
var proxy = configProxy;
|
let proxy = configProxy;
|
||||||
if (!proxy && proxy !== false) {
|
if (!proxy && proxy !== false) {
|
||||||
var proxyUrl = getProxyForUrl(location);
|
const proxyUrl = getProxyForUrl(location);
|
||||||
if (proxyUrl) {
|
if (proxyUrl) {
|
||||||
proxy = url.parse(proxyUrl);
|
proxy = url.parse(proxyUrl);
|
||||||
// replace 'host' since the proxy object is not a URL object
|
// replace 'host' since the proxy object is not a URL object
|
||||||
@@ -68,7 +74,7 @@ function setProxy(options, configProxy, location) {
|
|||||||
if (proxy.auth.username || proxy.auth.password) {
|
if (proxy.auth.username || proxy.auth.password) {
|
||||||
proxy.auth = (proxy.auth.username || '') + ':' + (proxy.auth.password || '');
|
proxy.auth = (proxy.auth.username || '') + ':' + (proxy.auth.password || '');
|
||||||
}
|
}
|
||||||
var base64 = Buffer
|
const base64 = Buffer
|
||||||
.from(proxy.auth, 'utf8')
|
.from(proxy.auth, 'utf8')
|
||||||
.toString('base64');
|
.toString('base64');
|
||||||
options.headers['Proxy-Authorization'] = 'Basic ' + base64;
|
options.headers['Proxy-Authorization'] = 'Basic ' + base64;
|
||||||
@@ -92,10 +98,25 @@ function setProxy(options, configProxy, location) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/*eslint consistent-return:0*/
|
/*eslint consistent-return:0*/
|
||||||
module.exports = function httpAdapter(config) {
|
export default function httpAdapter(config) {
|
||||||
return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) {
|
return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) {
|
||||||
var onCanceled;
|
let onCanceled;
|
||||||
function done() {
|
let data = config.data;
|
||||||
|
const responseType = config.responseType;
|
||||||
|
const responseEncoding = config.responseEncoding;
|
||||||
|
const method = config.method.toUpperCase();
|
||||||
|
let isFinished;
|
||||||
|
let isDone;
|
||||||
|
let rejected = false;
|
||||||
|
let req;
|
||||||
|
|
||||||
|
// temporary internal emitter until the AxiosRequest class will be implemented
|
||||||
|
const emitter = new EventEmitter();
|
||||||
|
|
||||||
|
function onFinished() {
|
||||||
|
if (isFinished) return;
|
||||||
|
isFinished = true;
|
||||||
|
|
||||||
if (config.cancelToken) {
|
if (config.cancelToken) {
|
||||||
config.cancelToken.unsubscribe(onCanceled);
|
config.cancelToken.unsubscribe(onCanceled);
|
||||||
}
|
}
|
||||||
@@ -103,36 +124,58 @@ module.exports = function httpAdapter(config) {
|
|||||||
if (config.signal) {
|
if (config.signal) {
|
||||||
config.signal.removeEventListener('abort', onCanceled);
|
config.signal.removeEventListener('abort', onCanceled);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
emitter.removeAllListeners();
|
||||||
}
|
}
|
||||||
var resolve = function resolve(value) {
|
|
||||||
done();
|
function done(value, isRejected) {
|
||||||
resolvePromise(value);
|
if (isDone) return;
|
||||||
|
|
||||||
|
isDone = true;
|
||||||
|
|
||||||
|
if (isRejected) {
|
||||||
|
rejected = true;
|
||||||
|
onFinished();
|
||||||
|
}
|
||||||
|
|
||||||
|
isRejected ? rejectPromise(value) : resolvePromise(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
const resolve = function resolve(value) {
|
||||||
|
done(value);
|
||||||
};
|
};
|
||||||
var rejected = false;
|
|
||||||
var reject = function reject(value) {
|
const reject = function reject(value) {
|
||||||
done();
|
done(value, true);
|
||||||
rejected = true;
|
|
||||||
rejectPromise(value);
|
|
||||||
};
|
};
|
||||||
var data = config.data;
|
|
||||||
var responseType = config.responseType;
|
function abort(reason) {
|
||||||
var responseEncoding = config.responseEncoding;
|
emitter.emit('abort', !reason || reason.type ? new CanceledError(null, config, req) : reason);
|
||||||
var method = config.method.toUpperCase();
|
}
|
||||||
|
|
||||||
|
emitter.once('abort', reject);
|
||||||
|
|
||||||
|
if (config.cancelToken || config.signal) {
|
||||||
|
config.cancelToken && config.cancelToken.subscribe(abort);
|
||||||
|
if (config.signal) {
|
||||||
|
config.signal.aborted ? abort() : config.signal.addEventListener('abort', abort);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Parse url
|
// Parse url
|
||||||
var fullPath = buildFullPath(config.baseURL, config.url);
|
const fullPath = buildFullPath(config.baseURL, config.url);
|
||||||
var parsed = url.parse(fullPath);
|
const parsed = url.parse(fullPath);
|
||||||
var protocol = parsed.protocol || supportedProtocols[0];
|
const protocol = parsed.protocol || supportedProtocols[0];
|
||||||
|
|
||||||
if (protocol === 'data:') {
|
if (protocol === 'data:') {
|
||||||
var convertedData;
|
let convertedData;
|
||||||
|
|
||||||
if (method !== 'GET') {
|
if (method !== 'GET') {
|
||||||
return settle(resolve, reject, {
|
return settle(resolve, reject, {
|
||||||
status: 405,
|
status: 405,
|
||||||
statusText: 'method not allowed',
|
statusText: 'method not allowed',
|
||||||
headers: {},
|
headers: {},
|
||||||
config: config
|
config
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -159,7 +202,7 @@ module.exports = function httpAdapter(config) {
|
|||||||
status: 200,
|
status: 200,
|
||||||
statusText: 'OK',
|
statusText: 'OK',
|
||||||
headers: {},
|
headers: {},
|
||||||
config: config
|
config
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -171,29 +214,23 @@ module.exports = function httpAdapter(config) {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
var headers = config.headers;
|
const headers = AxiosHeaders.from(config.headers).normalize();
|
||||||
var headerNames = {};
|
|
||||||
|
|
||||||
Object.keys(headers).forEach(function storeLowerName(name) {
|
|
||||||
headerNames[name.toLowerCase()] = name;
|
|
||||||
});
|
|
||||||
|
|
||||||
// Set User-Agent (required by some servers)
|
// Set User-Agent (required by some servers)
|
||||||
// See https://github.com/axios/axios/issues/69
|
// See https://github.com/axios/axios/issues/69
|
||||||
if ('user-agent' in headerNames) {
|
// User-Agent is specified; handle case where no UA header is desired
|
||||||
// User-Agent is specified; handle case where no UA header is desired
|
// Only set header if it hasn't been set in config
|
||||||
if (!headers[headerNames['user-agent']]) {
|
headers.set('User-Agent', 'axios/' + VERSION, false);
|
||||||
delete headers[headerNames['user-agent']];
|
|
||||||
}
|
const onDownloadProgress = config.onDownloadProgress;
|
||||||
// Otherwise, use specified value
|
const onUploadProgress = config.onUploadProgress;
|
||||||
} else {
|
const maxRate = config.maxRate;
|
||||||
// Only set header if it hasn't been set in config
|
let maxUploadRate = undefined;
|
||||||
headers['User-Agent'] = 'axios/' + VERSION;
|
let maxDownloadRate = undefined;
|
||||||
}
|
|
||||||
|
|
||||||
// support for https://www.npmjs.com/package/form-data api
|
// support for https://www.npmjs.com/package/form-data api
|
||||||
if (utils.isFormData(data) && utils.isFunction(data.getHeaders)) {
|
if (utils.isFormData(data) && utils.isFunction(data.getHeaders)) {
|
||||||
Object.assign(headers, data.getHeaders());
|
headers.set(data.getHeaders());
|
||||||
} else if (data && !utils.isStream(data)) {
|
} else if (data && !utils.isStream(data)) {
|
||||||
if (Buffer.isBuffer(data)) {
|
if (Buffer.isBuffer(data)) {
|
||||||
// Nothing to do...
|
// Nothing to do...
|
||||||
@@ -209,6 +246,9 @@ module.exports = function httpAdapter(config) {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Add Content-Length header if data exists
|
||||||
|
headers.set('Content-Length', data.length, false);
|
||||||
|
|
||||||
if (config.maxBodyLength > -1 && data.length > config.maxBodyLength) {
|
if (config.maxBodyLength > -1 && data.length > config.maxBodyLength) {
|
||||||
return reject(new AxiosError(
|
return reject(new AxiosError(
|
||||||
'Request body larger than maxBodyLength limit',
|
'Request body larger than maxBodyLength limit',
|
||||||
@@ -216,49 +256,70 @@ module.exports = function httpAdapter(config) {
|
|||||||
config
|
config
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Add Content-Length header if data exists
|
const contentLength = +headers.getContentLength();
|
||||||
if (!headerNames['content-length']) {
|
|
||||||
headers['Content-Length'] = data.length;
|
if (utils.isArray(maxRate)) {
|
||||||
|
maxUploadRate = maxRate[0];
|
||||||
|
maxDownloadRate = maxRate[1];
|
||||||
|
} else {
|
||||||
|
maxUploadRate = maxDownloadRate = maxRate;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data && (onUploadProgress || maxUploadRate)) {
|
||||||
|
if (!utils.isStream(data)) {
|
||||||
|
data = stream.Readable.from(data, {objectMode: false});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
data = stream.pipeline([data, new AxiosTransformStream({
|
||||||
|
length: utils.toFiniteNumber(contentLength),
|
||||||
|
maxRate: utils.toFiniteNumber(maxUploadRate)
|
||||||
|
})], utils.noop);
|
||||||
|
|
||||||
|
onUploadProgress && data.on('progress', progress => {
|
||||||
|
onUploadProgress(Object.assign(progress, {
|
||||||
|
upload: true
|
||||||
|
}));
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// HTTP basic authentication
|
// HTTP basic authentication
|
||||||
var auth = undefined;
|
let auth = undefined;
|
||||||
if (config.auth) {
|
if (config.auth) {
|
||||||
var username = config.auth.username || '';
|
const username = config.auth.username || '';
|
||||||
var password = config.auth.password || '';
|
const password = config.auth.password || '';
|
||||||
auth = username + ':' + password;
|
auth = username + ':' + password;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!auth && parsed.auth) {
|
if (!auth && parsed.auth) {
|
||||||
var urlAuth = parsed.auth.split(':');
|
const urlAuth = parsed.auth.split(':');
|
||||||
var urlUsername = urlAuth[0] || '';
|
const urlUsername = urlAuth[0] || '';
|
||||||
var urlPassword = urlAuth[1] || '';
|
const urlPassword = urlAuth[1] || '';
|
||||||
auth = urlUsername + ':' + urlPassword;
|
auth = urlUsername + ':' + urlPassword;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (auth && headerNames.authorization) {
|
auth && headers.delete('authorization');
|
||||||
delete headers[headerNames.authorization];
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, '');
|
buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, '');
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
var customErr = new Error(err.message);
|
const customErr = new Error(err.message);
|
||||||
customErr.config = config;
|
customErr.config = config;
|
||||||
customErr.url = config.url;
|
customErr.url = config.url;
|
||||||
customErr.exists = true;
|
customErr.exists = true;
|
||||||
reject(customErr);
|
return reject(customErr);
|
||||||
}
|
}
|
||||||
|
|
||||||
var options = {
|
headers.set('Accept-Encoding', 'gzip, deflate, gzip, br', false);
|
||||||
|
|
||||||
|
const options = {
|
||||||
path: buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, ''),
|
path: buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, ''),
|
||||||
method: method,
|
method,
|
||||||
headers: headers,
|
headers: headers.toJSON(),
|
||||||
agents: { http: config.httpAgent, https: config.httpsAgent },
|
agents: { http: config.httpAgent, https: config.httpsAgent },
|
||||||
auth: auth,
|
auth,
|
||||||
protocol: protocol,
|
protocol,
|
||||||
beforeRedirect: dispatchBeforeRedirect,
|
beforeRedirect: dispatchBeforeRedirect,
|
||||||
beforeRedirects: {}
|
beforeRedirects: {}
|
||||||
};
|
};
|
||||||
@@ -271,8 +332,8 @@ module.exports = function httpAdapter(config) {
|
|||||||
setProxy(options, config.proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path);
|
setProxy(options, config.proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path);
|
||||||
}
|
}
|
||||||
|
|
||||||
var transport;
|
let transport;
|
||||||
var isHttpsRequest = isHttps.test(options.protocol);
|
const isHttpsRequest = isHttps.test(options.protocol);
|
||||||
options.agent = isHttpsRequest ? config.httpsAgent : config.httpAgent;
|
options.agent = isHttpsRequest ? config.httpsAgent : config.httpAgent;
|
||||||
if (config.transport) {
|
if (config.transport) {
|
||||||
transport = config.transport;
|
transport = config.transport;
|
||||||
@@ -300,14 +361,16 @@ module.exports = function httpAdapter(config) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Create the request
|
// Create the request
|
||||||
var req = transport.request(options, function handleResponse(res) {
|
req = transport.request(options, function handleResponse(res) {
|
||||||
if (req.aborted) return;
|
if (req.destroyed) return;
|
||||||
|
|
||||||
|
const streams = [res];
|
||||||
|
|
||||||
// uncompress the response body transparently if required
|
// uncompress the response body transparently if required
|
||||||
var responseStream = res;
|
let responseStream = res;
|
||||||
|
|
||||||
// return the last request in case of redirects
|
// return the last request in case of redirects
|
||||||
var lastRequest = res.req || req;
|
const lastRequest = res.req || req;
|
||||||
|
|
||||||
// if decompress disabled we should not decompress
|
// if decompress disabled we should not decompress
|
||||||
if (config.decompress !== false) {
|
if (config.decompress !== false) {
|
||||||
@@ -323,19 +386,48 @@ module.exports = function httpAdapter(config) {
|
|||||||
case 'compress':
|
case 'compress':
|
||||||
case 'deflate':
|
case 'deflate':
|
||||||
// add the unzipper to the body stream processing pipeline
|
// add the unzipper to the body stream processing pipeline
|
||||||
responseStream = responseStream.pipe(zlib.createUnzip());
|
streams.push(zlib.createUnzip());
|
||||||
|
|
||||||
// remove the content-encoding in order to not confuse downstream operations
|
// remove the content-encoding in order to not confuse downstream operations
|
||||||
delete res.headers['content-encoding'];
|
delete res.headers['content-encoding'];
|
||||||
break;
|
break;
|
||||||
|
case 'br':
|
||||||
|
if (isBrotliSupported) {
|
||||||
|
streams.push(zlib.createBrotliDecompress());
|
||||||
|
delete res.headers['content-encoding'];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var response = {
|
if (onDownloadProgress) {
|
||||||
|
const responseLength = +res.headers['content-length'];
|
||||||
|
|
||||||
|
const transformStream = new AxiosTransformStream({
|
||||||
|
length: utils.toFiniteNumber(responseLength),
|
||||||
|
maxRate: utils.toFiniteNumber(maxDownloadRate)
|
||||||
|
});
|
||||||
|
|
||||||
|
onDownloadProgress && transformStream.on('progress', progress => {
|
||||||
|
onDownloadProgress(Object.assign(progress, {
|
||||||
|
download: true
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
|
streams.push(transformStream);
|
||||||
|
}
|
||||||
|
|
||||||
|
responseStream = streams.length > 1 ? stream.pipeline(streams, utils.noop) : streams[0];
|
||||||
|
|
||||||
|
const offListeners = stream.finished(responseStream, () => {
|
||||||
|
offListeners();
|
||||||
|
onFinished();
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = {
|
||||||
status: res.statusCode,
|
status: res.statusCode,
|
||||||
statusText: res.statusMessage,
|
statusText: res.statusMessage,
|
||||||
headers: res.headers,
|
headers: new AxiosHeaders(res.headers),
|
||||||
config: config,
|
config,
|
||||||
request: lastRequest
|
request: lastRequest
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -343,8 +435,9 @@ module.exports = function httpAdapter(config) {
|
|||||||
response.data = responseStream;
|
response.data = responseStream;
|
||||||
settle(resolve, reject, response);
|
settle(resolve, reject, response);
|
||||||
} else {
|
} else {
|
||||||
var responseBuffer = [];
|
const responseBuffer = [];
|
||||||
var totalResponseBytes = 0;
|
let totalResponseBytes = 0;
|
||||||
|
|
||||||
responseStream.on('data', function handleStreamData(chunk) {
|
responseStream.on('data', function handleStreamData(chunk) {
|
||||||
responseBuffer.push(chunk);
|
responseBuffer.push(chunk);
|
||||||
totalResponseBytes += chunk.length;
|
totalResponseBytes += chunk.length;
|
||||||
@@ -363,23 +456,25 @@ module.exports = function httpAdapter(config) {
|
|||||||
if (rejected) {
|
if (rejected) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
responseStream.destroy();
|
|
||||||
reject(new AxiosError(
|
const err = new AxiosError(
|
||||||
'maxContentLength size of ' + config.maxContentLength + ' exceeded',
|
'maxContentLength size of ' + config.maxContentLength + ' exceeded',
|
||||||
AxiosError.ERR_BAD_RESPONSE,
|
AxiosError.ERR_BAD_RESPONSE,
|
||||||
config,
|
config,
|
||||||
lastRequest
|
lastRequest
|
||||||
));
|
);
|
||||||
|
responseStream.destroy(err);
|
||||||
|
reject(err);
|
||||||
});
|
});
|
||||||
|
|
||||||
responseStream.on('error', function handleStreamError(err) {
|
responseStream.on('error', function handleStreamError(err) {
|
||||||
if (req.aborted) return;
|
if (req.destroyed) return;
|
||||||
reject(AxiosError.from(err, null, config, lastRequest));
|
reject(AxiosError.from(err, null, config, lastRequest));
|
||||||
});
|
});
|
||||||
|
|
||||||
responseStream.on('end', function handleStreamEnd() {
|
responseStream.on('end', function handleStreamEnd() {
|
||||||
try {
|
try {
|
||||||
var responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer);
|
let responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer);
|
||||||
if (responseType !== 'arraybuffer') {
|
if (responseType !== 'arraybuffer') {
|
||||||
responseData = responseData.toString(responseEncoding);
|
responseData = responseData.toString(responseEncoding);
|
||||||
if (!responseEncoding || responseEncoding === 'utf8') {
|
if (!responseEncoding || responseEncoding === 'utf8') {
|
||||||
@@ -393,6 +488,18 @@ module.exports = function httpAdapter(config) {
|
|||||||
settle(resolve, reject, response);
|
settle(resolve, reject, response);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
emitter.once('abort', err => {
|
||||||
|
if (!responseStream.destroyed) {
|
||||||
|
responseStream.emit('error', err);
|
||||||
|
responseStream.destroy();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
emitter.once('abort', err => {
|
||||||
|
reject(err);
|
||||||
|
req.destroy(err);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Handle errors
|
// Handle errors
|
||||||
@@ -411,7 +518,7 @@ module.exports = function httpAdapter(config) {
|
|||||||
// Handle request timeout
|
// Handle request timeout
|
||||||
if (config.timeout) {
|
if (config.timeout) {
|
||||||
// This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types.
|
// This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types.
|
||||||
var timeout = parseInt(config.timeout, 10);
|
const timeout = parseInt(config.timeout, 10);
|
||||||
|
|
||||||
if (isNaN(timeout)) {
|
if (isNaN(timeout)) {
|
||||||
reject(new AxiosError(
|
reject(new AxiosError(
|
||||||
@@ -430,9 +537,9 @@ module.exports = function httpAdapter(config) {
|
|||||||
// And then these socket which be hang up will devouring CPU little by little.
|
// And then these socket which be hang up will devouring CPU little by little.
|
||||||
// ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect.
|
// ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect.
|
||||||
req.setTimeout(timeout, function handleRequestTimeout() {
|
req.setTimeout(timeout, function handleRequestTimeout() {
|
||||||
req.abort();
|
if (isDone) return;
|
||||||
var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
|
let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
|
||||||
var transitional = config.transitional || transitionalDefaults;
|
const transitional = config.transitional || transitionalDefaults;
|
||||||
if (config.timeoutErrorMessage) {
|
if (config.timeoutErrorMessage) {
|
||||||
timeoutErrorMessage = config.timeoutErrorMessage;
|
timeoutErrorMessage = config.timeoutErrorMessage;
|
||||||
}
|
}
|
||||||
@@ -442,33 +549,34 @@ module.exports = function httpAdapter(config) {
|
|||||||
config,
|
config,
|
||||||
req
|
req
|
||||||
));
|
));
|
||||||
|
abort();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (config.cancelToken || config.signal) {
|
|
||||||
// Handle cancellation
|
|
||||||
// eslint-disable-next-line func-names
|
|
||||||
onCanceled = function(cancel) {
|
|
||||||
if (req.aborted) return;
|
|
||||||
|
|
||||||
req.abort();
|
|
||||||
reject(!cancel || cancel.type ? new CanceledError(null, config, req) : cancel);
|
|
||||||
};
|
|
||||||
|
|
||||||
config.cancelToken && config.cancelToken.subscribe(onCanceled);
|
|
||||||
if (config.signal) {
|
|
||||||
config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// Send the request
|
// Send the request
|
||||||
if (utils.isStream(data)) {
|
if (utils.isStream(data)) {
|
||||||
data.on('error', function handleStreamError(err) {
|
let ended = false;
|
||||||
reject(AxiosError.from(err, config, null, req));
|
let errored = false;
|
||||||
}).pipe(req);
|
|
||||||
|
data.on('end', () => {
|
||||||
|
ended = true;
|
||||||
|
});
|
||||||
|
|
||||||
|
data.once('error', err => {
|
||||||
|
errored = true;
|
||||||
|
req.destroy(err);
|
||||||
|
});
|
||||||
|
|
||||||
|
data.on('close', () => {
|
||||||
|
if (!ended && !errored) {
|
||||||
|
abort(new CanceledError('Request stream has been aborted', config, req));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
data.pipe(req);
|
||||||
} else {
|
} else {
|
||||||
req.end(data);
|
req.end(data);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
};
|
}
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import utils from '../utils.js';
|
||||||
|
import httpAdapter from './http.js';
|
||||||
|
import xhrAdapter from './xhr.js';
|
||||||
|
|
||||||
|
const adapters = {
|
||||||
|
http: httpAdapter,
|
||||||
|
xhr: xhrAdapter
|
||||||
|
}
|
||||||
|
|
||||||
|
export default {
|
||||||
|
getAdapter: (nameOrAdapter) => {
|
||||||
|
if(utils.isString(nameOrAdapter)){
|
||||||
|
const adapter = adapters[nameOrAdapter];
|
||||||
|
|
||||||
|
if (!nameOrAdapter) {
|
||||||
|
throw Error(
|
||||||
|
utils.hasOwnProp(nameOrAdapter) ?
|
||||||
|
`Adapter '${nameOrAdapter}' is not available in the build` :
|
||||||
|
`Can not resolve adapter '${nameOrAdapter}'`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return adapter
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!utils.isFunction(nameOrAdapter)) {
|
||||||
|
throw new TypeError('adapter is not a function');
|
||||||
|
}
|
||||||
|
|
||||||
|
return nameOrAdapter;
|
||||||
|
},
|
||||||
|
adapters
|
||||||
|
}
|
||||||
+75
-48
@@ -1,24 +1,53 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var utils = require('./../utils');
|
import utils from './../utils.js';
|
||||||
var settle = require('./../core/settle');
|
import settle from './../core/settle.js';
|
||||||
var cookies = require('./../helpers/cookies');
|
import cookies from './../helpers/cookies.js';
|
||||||
var buildURL = require('./../helpers/buildURL');
|
import buildURL from './../helpers/buildURL.js';
|
||||||
var buildFullPath = require('../core/buildFullPath');
|
import buildFullPath from '../core/buildFullPath.js';
|
||||||
var parseHeaders = require('./../helpers/parseHeaders');
|
import isURLSameOrigin from './../helpers/isURLSameOrigin.js';
|
||||||
var isURLSameOrigin = require('./../helpers/isURLSameOrigin');
|
import transitionalDefaults from '../defaults/transitional.js';
|
||||||
var transitionalDefaults = require('../defaults/transitional');
|
import AxiosError from '../core/AxiosError.js';
|
||||||
var AxiosError = require('../core/AxiosError');
|
import CanceledError from '../cancel/CanceledError.js';
|
||||||
var CanceledError = require('../cancel/CanceledError');
|
import parseProtocol from '../helpers/parseProtocol.js';
|
||||||
var parseProtocol = require('../helpers/parseProtocol');
|
import platform from '../platform/index.js';
|
||||||
var platform = require('../platform');
|
import AxiosHeaders from '../core/AxiosHeaders.js';
|
||||||
|
import speedometer from '../helpers/speedometer.js';
|
||||||
|
|
||||||
module.exports = function xhrAdapter(config) {
|
function progressEventReducer(listener, isDownloadStream) {
|
||||||
|
let bytesNotified = 0;
|
||||||
|
const _speedometer = speedometer(50, 250);
|
||||||
|
|
||||||
|
return e => {
|
||||||
|
const loaded = e.loaded;
|
||||||
|
const total = e.lengthComputable ? e.total : undefined;
|
||||||
|
const progressBytes = loaded - bytesNotified;
|
||||||
|
const rate = _speedometer(progressBytes);
|
||||||
|
const inRange = loaded <= total;
|
||||||
|
|
||||||
|
bytesNotified = loaded;
|
||||||
|
|
||||||
|
const data = {
|
||||||
|
loaded,
|
||||||
|
total,
|
||||||
|
progress: total ? (loaded / total) : undefined,
|
||||||
|
bytes: progressBytes,
|
||||||
|
rate: rate ? rate : undefined,
|
||||||
|
estimated: rate && total && inRange ? (total - loaded) / rate : undefined
|
||||||
|
};
|
||||||
|
|
||||||
|
data[isDownloadStream ? 'download' : 'upload'] = true;
|
||||||
|
|
||||||
|
listener(data);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function xhrAdapter(config) {
|
||||||
return new Promise(function dispatchXhrRequest(resolve, reject) {
|
return new Promise(function dispatchXhrRequest(resolve, reject) {
|
||||||
var requestData = config.data;
|
let requestData = config.data;
|
||||||
var requestHeaders = config.headers;
|
const requestHeaders = AxiosHeaders.from(config.headers).normalize();
|
||||||
var responseType = config.responseType;
|
const responseType = config.responseType;
|
||||||
var onCanceled;
|
let onCanceled;
|
||||||
function done() {
|
function done() {
|
||||||
if (config.cancelToken) {
|
if (config.cancelToken) {
|
||||||
config.cancelToken.unsubscribe(onCanceled);
|
config.cancelToken.unsubscribe(onCanceled);
|
||||||
@@ -30,19 +59,19 @@ module.exports = function xhrAdapter(config) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (utils.isFormData(requestData) && utils.isStandardBrowserEnv()) {
|
if (utils.isFormData(requestData) && utils.isStandardBrowserEnv()) {
|
||||||
delete requestHeaders['Content-Type']; // Let the browser set it
|
requestHeaders.setContentType(false); // Let the browser set it
|
||||||
}
|
}
|
||||||
|
|
||||||
var request = new XMLHttpRequest();
|
let request = new XMLHttpRequest();
|
||||||
|
|
||||||
// HTTP basic authentication
|
// HTTP basic authentication
|
||||||
if (config.auth) {
|
if (config.auth) {
|
||||||
var username = config.auth.username || '';
|
const username = config.auth.username || '';
|
||||||
var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
|
const password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
|
||||||
requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
|
requestHeaders.set('Authorization', 'Basic ' + btoa(username + ':' + password));
|
||||||
}
|
}
|
||||||
|
|
||||||
var fullPath = buildFullPath(config.baseURL, config.url);
|
const fullPath = buildFullPath(config.baseURL, config.url);
|
||||||
|
|
||||||
request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
|
request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
|
||||||
|
|
||||||
@@ -54,16 +83,18 @@ module.exports = function xhrAdapter(config) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// Prepare the response
|
// Prepare the response
|
||||||
var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
|
const responseHeaders = AxiosHeaders.from(
|
||||||
var responseData = !responseType || responseType === 'text' || responseType === 'json' ?
|
'getAllResponseHeaders' in request && request.getAllResponseHeaders()
|
||||||
|
);
|
||||||
|
const responseData = !responseType || responseType === 'text' || responseType === 'json' ?
|
||||||
request.responseText : request.response;
|
request.responseText : request.response;
|
||||||
var response = {
|
const response = {
|
||||||
data: responseData,
|
data: responseData,
|
||||||
status: request.status,
|
status: request.status,
|
||||||
statusText: request.statusText,
|
statusText: request.statusText,
|
||||||
headers: responseHeaders,
|
headers: responseHeaders,
|
||||||
config: config,
|
config,
|
||||||
request: request
|
request
|
||||||
};
|
};
|
||||||
|
|
||||||
settle(function _resolve(value) {
|
settle(function _resolve(value) {
|
||||||
@@ -125,8 +156,8 @@ module.exports = function xhrAdapter(config) {
|
|||||||
|
|
||||||
// Handle timeout
|
// Handle timeout
|
||||||
request.ontimeout = function handleTimeout() {
|
request.ontimeout = function handleTimeout() {
|
||||||
var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
|
let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
|
||||||
var transitional = config.transitional || transitionalDefaults;
|
const transitional = config.transitional || transitionalDefaults;
|
||||||
if (config.timeoutErrorMessage) {
|
if (config.timeoutErrorMessage) {
|
||||||
timeoutErrorMessage = config.timeoutErrorMessage;
|
timeoutErrorMessage = config.timeoutErrorMessage;
|
||||||
}
|
}
|
||||||
@@ -145,25 +176,21 @@ module.exports = function xhrAdapter(config) {
|
|||||||
// Specifically not if we're in a web worker, or react-native.
|
// Specifically not if we're in a web worker, or react-native.
|
||||||
if (utils.isStandardBrowserEnv()) {
|
if (utils.isStandardBrowserEnv()) {
|
||||||
// Add xsrf header
|
// Add xsrf header
|
||||||
var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
|
const xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath))
|
||||||
cookies.read(config.xsrfCookieName) :
|
&& config.xsrfCookieName && cookies.read(config.xsrfCookieName);
|
||||||
undefined;
|
|
||||||
|
|
||||||
if (xsrfValue) {
|
if (xsrfValue) {
|
||||||
requestHeaders[config.xsrfHeaderName] = xsrfValue;
|
requestHeaders.set(config.xsrfHeaderName, xsrfValue);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Remove Content-Type if data is undefined
|
||||||
|
requestData === undefined && requestHeaders.setContentType(null);
|
||||||
|
|
||||||
// Add headers to the request
|
// Add headers to the request
|
||||||
if ('setRequestHeader' in request) {
|
if ('setRequestHeader' in request) {
|
||||||
utils.forEach(requestHeaders, function setRequestHeader(val, key) {
|
utils.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
|
||||||
if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
|
request.setRequestHeader(key, val);
|
||||||
// Remove Content-Type if data is undefined
|
|
||||||
delete requestHeaders[key];
|
|
||||||
} else {
|
|
||||||
// Otherwise add header to the request
|
|
||||||
request.setRequestHeader(key, val);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -179,22 +206,22 @@ module.exports = function xhrAdapter(config) {
|
|||||||
|
|
||||||
// Handle progress if needed
|
// Handle progress if needed
|
||||||
if (typeof config.onDownloadProgress === 'function') {
|
if (typeof config.onDownloadProgress === 'function') {
|
||||||
request.addEventListener('progress', config.onDownloadProgress);
|
request.addEventListener('progress', progressEventReducer(config.onDownloadProgress, true));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Not all browsers support upload events
|
// Not all browsers support upload events
|
||||||
if (typeof config.onUploadProgress === 'function' && request.upload) {
|
if (typeof config.onUploadProgress === 'function' && request.upload) {
|
||||||
request.upload.addEventListener('progress', config.onUploadProgress);
|
request.upload.addEventListener('progress', progressEventReducer(config.onUploadProgress));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (config.cancelToken || config.signal) {
|
if (config.cancelToken || config.signal) {
|
||||||
// Handle cancellation
|
// Handle cancellation
|
||||||
// eslint-disable-next-line func-names
|
// eslint-disable-next-line func-names
|
||||||
onCanceled = function(cancel) {
|
onCanceled = cancel => {
|
||||||
if (!request) {
|
if (!request) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
reject(!cancel || cancel.type ? new CanceledError(null, config, req) : cancel);
|
reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);
|
||||||
request.abort();
|
request.abort();
|
||||||
request = null;
|
request = null;
|
||||||
};
|
};
|
||||||
@@ -210,7 +237,7 @@ module.exports = function xhrAdapter(config) {
|
|||||||
requestData = null;
|
requestData = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
var protocol = parseProtocol(fullPath);
|
const protocol = parseProtocol(fullPath);
|
||||||
|
|
||||||
if (protocol && platform.protocols.indexOf(protocol) === -1) {
|
if (protocol && platform.protocols.indexOf(protocol) === -1) {
|
||||||
reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));
|
reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));
|
||||||
@@ -221,4 +248,4 @@ module.exports = function xhrAdapter(config) {
|
|||||||
// Send the request
|
// Send the request
|
||||||
request.send(requestData);
|
request.send(requestData);
|
||||||
});
|
});
|
||||||
};
|
}
|
||||||
|
|||||||
+31
-24
@@ -1,11 +1,20 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var utils = require('./utils');
|
import utils from './utils.js';
|
||||||
var bind = require('./helpers/bind');
|
import bind from './helpers/bind.js';
|
||||||
var Axios = require('./core/Axios');
|
import Axios from './core/Axios.js';
|
||||||
var mergeConfig = require('./core/mergeConfig');
|
import mergeConfig from './core/mergeConfig.js';
|
||||||
var defaults = require('./defaults');
|
import defaults from './defaults/index.js';
|
||||||
var formDataToJSON = require('./helpers/formDataToJSON');
|
import formDataToJSON from './helpers/formDataToJSON.js';
|
||||||
|
import CanceledError from './cancel/CanceledError.js';
|
||||||
|
import CancelToken from'./cancel/CancelToken.js';
|
||||||
|
import isCancel from'./cancel/isCancel.js';
|
||||||
|
import {VERSION} from './env/data.js';
|
||||||
|
import toFormData from './helpers/toFormData.js';
|
||||||
|
import AxiosError from '../lib/core/AxiosError.js';
|
||||||
|
import spread from './helpers/spread.js';
|
||||||
|
import isAxiosError from './helpers/isAxiosError.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create an instance of Axios
|
* Create an instance of Axios
|
||||||
*
|
*
|
||||||
@@ -14,14 +23,14 @@ var formDataToJSON = require('./helpers/formDataToJSON');
|
|||||||
* @returns {Axios} A new instance of Axios
|
* @returns {Axios} A new instance of Axios
|
||||||
*/
|
*/
|
||||||
function createInstance(defaultConfig) {
|
function createInstance(defaultConfig) {
|
||||||
var context = new Axios(defaultConfig);
|
const context = new Axios(defaultConfig);
|
||||||
var instance = bind(Axios.prototype.request, context);
|
const instance = bind(Axios.prototype.request, context);
|
||||||
|
|
||||||
// Copy axios.prototype to instance
|
// Copy axios.prototype to instance
|
||||||
utils.extend(instance, Axios.prototype, context);
|
utils.extend(instance, Axios.prototype, context, {allOwnKeys: true});
|
||||||
|
|
||||||
// Copy context to instance
|
// Copy context to instance
|
||||||
utils.extend(instance, context);
|
utils.extend(instance, context, {allOwnKeys: true});
|
||||||
|
|
||||||
// Factory for creating new instances
|
// Factory for creating new instances
|
||||||
instance.create = function create(instanceConfig) {
|
instance.create = function create(instanceConfig) {
|
||||||
@@ -32,20 +41,20 @@ function createInstance(defaultConfig) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Create the default instance to be exported
|
// Create the default instance to be exported
|
||||||
var axios = createInstance(defaults);
|
const axios = createInstance(defaults);
|
||||||
|
|
||||||
// Expose Axios class to allow class inheritance
|
// Expose Axios class to allow class inheritance
|
||||||
axios.Axios = Axios;
|
axios.Axios = Axios;
|
||||||
|
|
||||||
// Expose Cancel & CancelToken
|
// Expose Cancel & CancelToken
|
||||||
axios.CanceledError = require('./cancel/CanceledError');
|
axios.CanceledError = CanceledError;
|
||||||
axios.CancelToken = require('./cancel/CancelToken');
|
axios.CancelToken = CancelToken;
|
||||||
axios.isCancel = require('./cancel/isCancel');
|
axios.isCancel = isCancel;
|
||||||
axios.VERSION = require('./env/data').version;
|
axios.VERSION = VERSION;
|
||||||
axios.toFormData = require('./helpers/toFormData');
|
axios.toFormData = toFormData;
|
||||||
|
|
||||||
// Expose AxiosError class
|
// Expose AxiosError class
|
||||||
axios.AxiosError = require('../lib/core/AxiosError');
|
axios.AxiosError = AxiosError;
|
||||||
|
|
||||||
// alias for CanceledError for backward compatibility
|
// alias for CanceledError for backward compatibility
|
||||||
axios.Cancel = axios.CanceledError;
|
axios.Cancel = axios.CanceledError;
|
||||||
@@ -54,16 +63,14 @@ axios.Cancel = axios.CanceledError;
|
|||||||
axios.all = function all(promises) {
|
axios.all = function all(promises) {
|
||||||
return Promise.all(promises);
|
return Promise.all(promises);
|
||||||
};
|
};
|
||||||
axios.spread = require('./helpers/spread');
|
|
||||||
|
axios.spread = spread;
|
||||||
|
|
||||||
// Expose isAxiosError
|
// Expose isAxiosError
|
||||||
axios.isAxiosError = require('./helpers/isAxiosError');
|
axios.isAxiosError = isAxiosError;
|
||||||
|
|
||||||
axios.formToJSON = function(thing) {
|
axios.formToJSON = thing => {
|
||||||
return formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
|
return formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = axios;
|
export default axios;
|
||||||
|
|
||||||
// Allow use of default import syntax in TypeScript
|
|
||||||
module.exports.default = axios;
|
|
||||||
|
|||||||
+99
-97
@@ -1,6 +1,6 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var CanceledError = require('./CanceledError');
|
import CanceledError from './CanceledError.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A `CancelToken` is an object that can be used to request cancellation of an operation.
|
* A `CancelToken` is an object that can be used to request cancellation of an operation.
|
||||||
@@ -9,111 +9,113 @@ var CanceledError = require('./CanceledError');
|
|||||||
*
|
*
|
||||||
* @returns {CancelToken}
|
* @returns {CancelToken}
|
||||||
*/
|
*/
|
||||||
function CancelToken(executor) {
|
class CancelToken {
|
||||||
if (typeof executor !== 'function') {
|
constructor(executor) {
|
||||||
throw new TypeError('executor must be a function.');
|
if (typeof executor !== 'function') {
|
||||||
}
|
throw new TypeError('executor must be a function.');
|
||||||
|
|
||||||
var resolvePromise;
|
|
||||||
|
|
||||||
this.promise = new Promise(function promiseExecutor(resolve) {
|
|
||||||
resolvePromise = resolve;
|
|
||||||
});
|
|
||||||
|
|
||||||
var token = this;
|
|
||||||
|
|
||||||
// eslint-disable-next-line func-names
|
|
||||||
this.promise.then(function(cancel) {
|
|
||||||
if (!token._listeners) return;
|
|
||||||
|
|
||||||
var i = token._listeners.length;
|
|
||||||
|
|
||||||
while (i-- > 0) {
|
|
||||||
token._listeners[i](cancel);
|
|
||||||
}
|
}
|
||||||
token._listeners = null;
|
|
||||||
});
|
|
||||||
|
|
||||||
// eslint-disable-next-line func-names
|
let resolvePromise;
|
||||||
this.promise.then = function(onfulfilled) {
|
|
||||||
var _resolve;
|
this.promise = new Promise(function promiseExecutor(resolve) {
|
||||||
|
resolvePromise = resolve;
|
||||||
|
});
|
||||||
|
|
||||||
|
const token = this;
|
||||||
|
|
||||||
// eslint-disable-next-line func-names
|
// eslint-disable-next-line func-names
|
||||||
var promise = new Promise(function(resolve) {
|
this.promise.then(cancel => {
|
||||||
token.subscribe(resolve);
|
if (!token._listeners) return;
|
||||||
_resolve = resolve;
|
|
||||||
}).then(onfulfilled);
|
|
||||||
|
|
||||||
promise.cancel = function reject() {
|
let i = token._listeners.length;
|
||||||
token.unsubscribe(_resolve);
|
|
||||||
|
while (i-- > 0) {
|
||||||
|
token._listeners[i](cancel);
|
||||||
|
}
|
||||||
|
token._listeners = null;
|
||||||
|
});
|
||||||
|
|
||||||
|
// eslint-disable-next-line func-names
|
||||||
|
this.promise.then = onfulfilled => {
|
||||||
|
let _resolve;
|
||||||
|
// eslint-disable-next-line func-names
|
||||||
|
const promise = new Promise(resolve => {
|
||||||
|
token.subscribe(resolve);
|
||||||
|
_resolve = resolve;
|
||||||
|
}).then(onfulfilled);
|
||||||
|
|
||||||
|
promise.cancel = function reject() {
|
||||||
|
token.unsubscribe(_resolve);
|
||||||
|
};
|
||||||
|
|
||||||
|
return promise;
|
||||||
};
|
};
|
||||||
|
|
||||||
return promise;
|
executor(function cancel(message, config, request) {
|
||||||
};
|
if (token.reason) {
|
||||||
|
// Cancellation has already been requested
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
executor(function cancel(message, config, request) {
|
token.reason = new CanceledError(message, config, request);
|
||||||
if (token.reason) {
|
resolvePromise(token.reason);
|
||||||
// Cancellation has already been requested
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Throws a `CanceledError` if cancellation has been requested.
|
||||||
|
*/
|
||||||
|
throwIfRequested() {
|
||||||
|
if (this.reason) {
|
||||||
|
throw this.reason;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Subscribe to the cancel signal
|
||||||
|
*/
|
||||||
|
|
||||||
|
subscribe(listener) {
|
||||||
|
if (this.reason) {
|
||||||
|
listener(this.reason);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
token.reason = new CanceledError(message, config, request);
|
if (this._listeners) {
|
||||||
resolvePromise(token.reason);
|
this._listeners.push(listener);
|
||||||
});
|
} else {
|
||||||
|
this._listeners = [listener];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unsubscribe from the cancel signal
|
||||||
|
*/
|
||||||
|
|
||||||
|
unsubscribe(listener) {
|
||||||
|
if (!this._listeners) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const index = this._listeners.indexOf(listener);
|
||||||
|
if (index !== -1) {
|
||||||
|
this._listeners.splice(index, 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns an object that contains a new `CancelToken` and a function that, when called,
|
||||||
|
* cancels the `CancelToken`.
|
||||||
|
*/
|
||||||
|
static source() {
|
||||||
|
let cancel;
|
||||||
|
const token = new CancelToken(function executor(c) {
|
||||||
|
cancel = c;
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
token,
|
||||||
|
cancel
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
export default CancelToken;
|
||||||
* Throws a `CanceledError` if cancellation has been requested.
|
|
||||||
*/
|
|
||||||
CancelToken.prototype.throwIfRequested = function throwIfRequested() {
|
|
||||||
if (this.reason) {
|
|
||||||
throw this.reason;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Subscribe to the cancel signal
|
|
||||||
*/
|
|
||||||
|
|
||||||
CancelToken.prototype.subscribe = function subscribe(listener) {
|
|
||||||
if (this.reason) {
|
|
||||||
listener(this.reason);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this._listeners) {
|
|
||||||
this._listeners.push(listener);
|
|
||||||
} else {
|
|
||||||
this._listeners = [listener];
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Unsubscribe from the cancel signal
|
|
||||||
*/
|
|
||||||
|
|
||||||
CancelToken.prototype.unsubscribe = function unsubscribe(listener) {
|
|
||||||
if (!this._listeners) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
var index = this._listeners.indexOf(listener);
|
|
||||||
if (index !== -1) {
|
|
||||||
this._listeners.splice(index, 1);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns an object that contains a new `CancelToken` and a function that, when called,
|
|
||||||
* cancels the `CancelToken`.
|
|
||||||
*/
|
|
||||||
CancelToken.source = function source() {
|
|
||||||
var cancel;
|
|
||||||
var token = new CancelToken(function executor(c) {
|
|
||||||
cancel = c;
|
|
||||||
});
|
|
||||||
return {
|
|
||||||
token: token,
|
|
||||||
cancel: cancel
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
module.exports = CancelToken;
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var AxiosError = require('../core/AxiosError');
|
import AxiosError from '../core/AxiosError.js';
|
||||||
var utils = require('../utils');
|
import utils from '../utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A `CanceledError` is an object that is thrown when an operation is canceled.
|
* A `CanceledError` is an object that is thrown when an operation is canceled.
|
||||||
@@ -22,4 +22,4 @@ utils.inherits(CanceledError, AxiosError, {
|
|||||||
__CANCEL__: true
|
__CANCEL__: true
|
||||||
});
|
});
|
||||||
|
|
||||||
module.exports = CanceledError;
|
export default CanceledError;
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
module.exports = function isCancel(value) {
|
export default function isCancel(value) {
|
||||||
return !!(value && value.__CANCEL__);
|
return !!(value && value.__CANCEL__);
|
||||||
};
|
}
|
||||||
|
|||||||
+133
-110
@@ -1,14 +1,16 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var utils = require('./../utils');
|
import utils from './../utils.js';
|
||||||
var buildURL = require('../helpers/buildURL');
|
import buildURL from '../helpers/buildURL.js';
|
||||||
var InterceptorManager = require('./InterceptorManager');
|
import InterceptorManager from './InterceptorManager.js';
|
||||||
var dispatchRequest = require('./dispatchRequest');
|
import dispatchRequest from './dispatchRequest.js';
|
||||||
var mergeConfig = require('./mergeConfig');
|
import mergeConfig from './mergeConfig.js';
|
||||||
var buildFullPath = require('./buildFullPath');
|
import buildFullPath from './buildFullPath.js';
|
||||||
var validator = require('../helpers/validator');
|
import validator from '../helpers/validator.js';
|
||||||
|
import AxiosHeaders from './AxiosHeaders.js';
|
||||||
|
|
||||||
|
const validators = validator.validators;
|
||||||
|
|
||||||
var validators = validator.validators;
|
|
||||||
/**
|
/**
|
||||||
* Create a new instance of Axios
|
* Create a new instance of Axios
|
||||||
*
|
*
|
||||||
@@ -16,126 +18,147 @@ var validators = validator.validators;
|
|||||||
*
|
*
|
||||||
* @return {Axios} A new instance of Axios
|
* @return {Axios} A new instance of Axios
|
||||||
*/
|
*/
|
||||||
function Axios(instanceConfig) {
|
class Axios {
|
||||||
this.defaults = instanceConfig;
|
constructor(instanceConfig) {
|
||||||
this.interceptors = {
|
this.defaults = instanceConfig;
|
||||||
request: new InterceptorManager(),
|
this.interceptors = {
|
||||||
response: new InterceptorManager()
|
request: new InterceptorManager(),
|
||||||
};
|
response: new InterceptorManager()
|
||||||
}
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* Dispatch a request
|
|
||||||
*
|
|
||||||
* @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
|
|
||||||
* @param {?Object} config
|
|
||||||
*
|
|
||||||
* @returns {Promise} The Promise to be fulfilled
|
|
||||||
*/
|
|
||||||
Axios.prototype.request = function request(configOrUrl, config) {
|
|
||||||
/*eslint no-param-reassign:0*/
|
|
||||||
// Allow for axios('example/url'[, config]) a la fetch API
|
|
||||||
if (typeof configOrUrl === 'string') {
|
|
||||||
config = config || {};
|
|
||||||
config.url = configOrUrl;
|
|
||||||
} else {
|
|
||||||
config = configOrUrl || {};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
config = mergeConfig(this.defaults, config);
|
/**
|
||||||
|
* Dispatch a request
|
||||||
// Set config.method
|
*
|
||||||
if (config.method) {
|
* @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
|
||||||
config.method = config.method.toLowerCase();
|
* @param {?Object} config
|
||||||
} else if (this.defaults.method) {
|
*
|
||||||
config.method = this.defaults.method.toLowerCase();
|
* @returns {Promise} The Promise to be fulfilled
|
||||||
} else {
|
*/
|
||||||
config.method = 'get';
|
request(configOrUrl, config) {
|
||||||
}
|
/*eslint no-param-reassign:0*/
|
||||||
|
// Allow for axios('example/url'[, config]) a la fetch API
|
||||||
var transitional = config.transitional;
|
if (typeof configOrUrl === 'string') {
|
||||||
|
config = config || {};
|
||||||
if (transitional !== undefined) {
|
config.url = configOrUrl;
|
||||||
validator.assertOptions(transitional, {
|
} else {
|
||||||
silentJSONParsing: validators.transitional(validators.boolean),
|
config = configOrUrl || {};
|
||||||
forcedJSONParsing: validators.transitional(validators.boolean),
|
|
||||||
clarifyTimeoutError: validators.transitional(validators.boolean)
|
|
||||||
}, false);
|
|
||||||
}
|
|
||||||
|
|
||||||
// filter out skipped interceptors
|
|
||||||
var requestInterceptorChain = [];
|
|
||||||
var synchronousRequestInterceptors = true;
|
|
||||||
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
|
|
||||||
if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
|
config = mergeConfig(this.defaults, config);
|
||||||
|
|
||||||
requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
|
const transitional = config.transitional;
|
||||||
});
|
|
||||||
|
|
||||||
var responseInterceptorChain = [];
|
if (transitional !== undefined) {
|
||||||
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
|
validator.assertOptions(transitional, {
|
||||||
responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
|
silentJSONParsing: validators.transitional(validators.boolean),
|
||||||
});
|
forcedJSONParsing: validators.transitional(validators.boolean),
|
||||||
|
clarifyTimeoutError: validators.transitional(validators.boolean)
|
||||||
|
}, false);
|
||||||
|
}
|
||||||
|
|
||||||
var promise;
|
// Set config.method
|
||||||
|
config.method = (config.method || this.defaults.method || 'get').toLowerCase();
|
||||||
|
|
||||||
if (!synchronousRequestInterceptors) {
|
// Flatten headers
|
||||||
var chain = [dispatchRequest, undefined];
|
const defaultHeaders = config.headers && utils.merge(
|
||||||
|
config.headers.common,
|
||||||
|
config.headers[config.method]
|
||||||
|
);
|
||||||
|
|
||||||
Array.prototype.unshift.apply(chain, requestInterceptorChain);
|
defaultHeaders && utils.forEach(
|
||||||
chain = chain.concat(responseInterceptorChain);
|
['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
|
||||||
|
function cleanHeaderConfig(method) {
|
||||||
|
delete config.headers[method];
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
promise = Promise.resolve(config);
|
config.headers = new AxiosHeaders(config.headers, defaultHeaders);
|
||||||
while (chain.length) {
|
|
||||||
promise = promise.then(chain.shift(), chain.shift());
|
// filter out skipped interceptors
|
||||||
|
const requestInterceptorChain = [];
|
||||||
|
let synchronousRequestInterceptors = true;
|
||||||
|
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
|
||||||
|
if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
|
||||||
|
|
||||||
|
requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
|
||||||
|
});
|
||||||
|
|
||||||
|
const responseInterceptorChain = [];
|
||||||
|
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
|
||||||
|
responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
|
||||||
|
});
|
||||||
|
|
||||||
|
let promise;
|
||||||
|
let i = 0;
|
||||||
|
let len;
|
||||||
|
|
||||||
|
if (!synchronousRequestInterceptors) {
|
||||||
|
const chain = [dispatchRequest.bind(this), undefined];
|
||||||
|
chain.unshift.apply(chain, requestInterceptorChain);
|
||||||
|
chain.push.apply(chain, responseInterceptorChain);
|
||||||
|
len = chain.length;
|
||||||
|
|
||||||
|
promise = Promise.resolve(config);
|
||||||
|
|
||||||
|
while (i < len) {
|
||||||
|
promise = promise.then(chain[i++], chain[i++]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return promise;
|
||||||
|
}
|
||||||
|
|
||||||
|
len = requestInterceptorChain.length;
|
||||||
|
|
||||||
|
let newConfig = config;
|
||||||
|
|
||||||
|
i = 0;
|
||||||
|
|
||||||
|
while (i < len) {
|
||||||
|
const onFulfilled = requestInterceptorChain[i++];
|
||||||
|
const onRejected = requestInterceptorChain[i++];
|
||||||
|
try {
|
||||||
|
newConfig = onFulfilled(newConfig);
|
||||||
|
} catch (error) {
|
||||||
|
onRejected.call(this, error);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
promise = dispatchRequest.call(this, newConfig);
|
||||||
|
} catch (error) {
|
||||||
|
return Promise.reject(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
i = 0;
|
||||||
|
len = responseInterceptorChain.length;
|
||||||
|
|
||||||
|
while (i < len) {
|
||||||
|
promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
|
||||||
}
|
}
|
||||||
|
|
||||||
return promise;
|
return promise;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
getUri(config) {
|
||||||
var newConfig = config;
|
config = mergeConfig(this.defaults, config);
|
||||||
while (requestInterceptorChain.length) {
|
const fullPath = buildFullPath(config.baseURL, config.url);
|
||||||
var onFulfilled = requestInterceptorChain.shift();
|
return buildURL(fullPath, config.params, config.paramsSerializer);
|
||||||
var onRejected = requestInterceptorChain.shift();
|
|
||||||
try {
|
|
||||||
newConfig = onFulfilled(newConfig);
|
|
||||||
} catch (error) {
|
|
||||||
onRejected(error);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
try {
|
|
||||||
promise = dispatchRequest(newConfig);
|
|
||||||
} catch (error) {
|
|
||||||
return Promise.reject(error);
|
|
||||||
}
|
|
||||||
|
|
||||||
while (responseInterceptorChain.length) {
|
|
||||||
promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift());
|
|
||||||
}
|
|
||||||
|
|
||||||
return promise;
|
|
||||||
};
|
|
||||||
|
|
||||||
Axios.prototype.getUri = function getUri(config) {
|
|
||||||
config = mergeConfig(this.defaults, config);
|
|
||||||
var fullPath = buildFullPath(config.baseURL, config.url);
|
|
||||||
return buildURL(fullPath, config.params, config.paramsSerializer);
|
|
||||||
};
|
|
||||||
|
|
||||||
// Provide aliases for supported request methods
|
// Provide aliases for supported request methods
|
||||||
utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
|
utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
|
||||||
/*eslint func-names:0*/
|
/*eslint func-names:0*/
|
||||||
Axios.prototype[method] = function(url, config) {
|
Axios.prototype[method] = function(url, config) {
|
||||||
return this.request(mergeConfig(config || {}, {
|
return this.request(mergeConfig(config || {}, {
|
||||||
method: method,
|
method,
|
||||||
url: url,
|
url,
|
||||||
data: (config || {}).data
|
data: (config || {}).data
|
||||||
}));
|
}));
|
||||||
};
|
};
|
||||||
@@ -147,12 +170,12 @@ utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
|
|||||||
function generateHTTPMethod(isForm) {
|
function generateHTTPMethod(isForm) {
|
||||||
return function httpMethod(url, data, config) {
|
return function httpMethod(url, data, config) {
|
||||||
return this.request(mergeConfig(config || {}, {
|
return this.request(mergeConfig(config || {}, {
|
||||||
method: method,
|
method,
|
||||||
headers: isForm ? {
|
headers: isForm ? {
|
||||||
'Content-Type': 'multipart/form-data'
|
'Content-Type': 'multipart/form-data'
|
||||||
} : {},
|
} : {},
|
||||||
url: url,
|
url,
|
||||||
data: data
|
data
|
||||||
}));
|
}));
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -162,4 +185,4 @@ utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
|
|||||||
Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
|
Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
module.exports = Axios;
|
export default Axios;
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var utils = require('../utils');
|
import utils from '../utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create an Error with the specified message, config, error code, request and response.
|
* Create an Error with the specified message, config, error code, request and response.
|
||||||
@@ -52,8 +52,8 @@ utils.inherits(AxiosError, Error, {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
var prototype = AxiosError.prototype;
|
const prototype = AxiosError.prototype;
|
||||||
var descriptors = {};
|
const descriptors = {};
|
||||||
|
|
||||||
[
|
[
|
||||||
'ERR_BAD_OPTION_VALUE',
|
'ERR_BAD_OPTION_VALUE',
|
||||||
@@ -69,7 +69,7 @@ var descriptors = {};
|
|||||||
'ERR_NOT_SUPPORT',
|
'ERR_NOT_SUPPORT',
|
||||||
'ERR_INVALID_URL'
|
'ERR_INVALID_URL'
|
||||||
// eslint-disable-next-line func-names
|
// eslint-disable-next-line func-names
|
||||||
].forEach(function(code) {
|
].forEach(code => {
|
||||||
descriptors[code] = {value: code};
|
descriptors[code] = {value: code};
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -77,11 +77,13 @@ Object.defineProperties(AxiosError, descriptors);
|
|||||||
Object.defineProperty(prototype, 'isAxiosError', {value: true});
|
Object.defineProperty(prototype, 'isAxiosError', {value: true});
|
||||||
|
|
||||||
// eslint-disable-next-line func-names
|
// eslint-disable-next-line func-names
|
||||||
AxiosError.from = function(error, code, config, request, response, customProps) {
|
AxiosError.from = (error, code, config, request, response, customProps) => {
|
||||||
var axiosError = Object.create(prototype);
|
const axiosError = Object.create(prototype);
|
||||||
|
|
||||||
utils.toFlatObject(error, axiosError, function filter(obj) {
|
utils.toFlatObject(error, axiosError, function filter(obj) {
|
||||||
return obj !== Error.prototype;
|
return obj !== Error.prototype;
|
||||||
|
}, prop => {
|
||||||
|
return prop !== 'isAxiosError';
|
||||||
});
|
});
|
||||||
|
|
||||||
AxiosError.call(axiosError, error.message, code, config, request, response);
|
AxiosError.call(axiosError, error.message, code, config, request, response);
|
||||||
@@ -95,4 +97,4 @@ AxiosError.from = function(error, code, config, request, response, customProps)
|
|||||||
return axiosError;
|
return axiosError;
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = AxiosError;
|
export default AxiosError;
|
||||||
|
|||||||
@@ -0,0 +1,274 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
import utils from '../utils.js';
|
||||||
|
import parseHeaders from '../helpers/parseHeaders.js';
|
||||||
|
|
||||||
|
const $internals = Symbol('internals');
|
||||||
|
const $defaults = Symbol('defaults');
|
||||||
|
|
||||||
|
function normalizeHeader(header) {
|
||||||
|
return header && String(header).trim().toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeValue(value) {
|
||||||
|
if (value === false || value == null) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
return String(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseTokens(str) {
|
||||||
|
const tokens = Object.create(null);
|
||||||
|
const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
|
||||||
|
let match;
|
||||||
|
|
||||||
|
while ((match = tokensRE.exec(str))) {
|
||||||
|
tokens[match[1]] = match[2];
|
||||||
|
}
|
||||||
|
|
||||||
|
return tokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
function matchHeaderValue(context, value, header, filter) {
|
||||||
|
if (utils.isFunction(filter)) {
|
||||||
|
return filter.call(this, value, header);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!utils.isString(value)) return;
|
||||||
|
|
||||||
|
if (utils.isString(filter)) {
|
||||||
|
return value.indexOf(filter) !== -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (utils.isRegExp(filter)) {
|
||||||
|
return filter.test(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatHeader(header) {
|
||||||
|
return header.trim()
|
||||||
|
.toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
|
||||||
|
return char.toUpperCase() + str;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildAccessors(obj, header) {
|
||||||
|
const accessorName = utils.toCamelCase(' ' + header);
|
||||||
|
|
||||||
|
['get', 'set', 'has'].forEach(methodName => {
|
||||||
|
Object.defineProperty(obj, methodName + accessorName, {
|
||||||
|
value: function(arg1, arg2, arg3) {
|
||||||
|
return this[methodName].call(this, header, arg1, arg2, arg3);
|
||||||
|
},
|
||||||
|
configurable: true
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function findKey(obj, key) {
|
||||||
|
key = key.toLowerCase();
|
||||||
|
const keys = Object.keys(obj);
|
||||||
|
let i = keys.length;
|
||||||
|
let _key;
|
||||||
|
while (i-- > 0) {
|
||||||
|
_key = keys[i];
|
||||||
|
if (key === _key.toLowerCase()) {
|
||||||
|
return _key;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function AxiosHeaders(headers, defaults) {
|
||||||
|
headers && this.set(headers);
|
||||||
|
this[$defaults] = defaults || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
Object.assign(AxiosHeaders.prototype, {
|
||||||
|
set: function(header, valueOrRewrite, rewrite) {
|
||||||
|
const self = this;
|
||||||
|
|
||||||
|
function setHeader(_value, _header, _rewrite) {
|
||||||
|
const lHeader = normalizeHeader(_header);
|
||||||
|
|
||||||
|
if (!lHeader) {
|
||||||
|
throw new Error('header name must be a non-empty string');
|
||||||
|
}
|
||||||
|
|
||||||
|
const key = findKey(self, lHeader);
|
||||||
|
|
||||||
|
if (key && _rewrite !== true && (self[key] === false || _rewrite === false)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (utils.isArray(_value)) {
|
||||||
|
_value = _value.map(normalizeValue);
|
||||||
|
} else {
|
||||||
|
_value = normalizeValue(_value);
|
||||||
|
}
|
||||||
|
|
||||||
|
self[key || _header] = _value;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (utils.isPlainObject(header)) {
|
||||||
|
utils.forEach(header, (_value, _header) => {
|
||||||
|
setHeader(_value, _header, valueOrRewrite);
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
setHeader(valueOrRewrite, header, rewrite);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this;
|
||||||
|
},
|
||||||
|
|
||||||
|
get: function(header, parser) {
|
||||||
|
header = normalizeHeader(header);
|
||||||
|
|
||||||
|
if (!header) return undefined;
|
||||||
|
|
||||||
|
const key = findKey(this, header);
|
||||||
|
|
||||||
|
if (key) {
|
||||||
|
const value = this[key];
|
||||||
|
|
||||||
|
if (!parser) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (parser === true) {
|
||||||
|
return parseTokens(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (utils.isFunction(parser)) {
|
||||||
|
return parser.call(this, value, key);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (utils.isRegExp(parser)) {
|
||||||
|
return parser.exec(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new TypeError('parser must be boolean|regexp|function');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
has: function(header, matcher) {
|
||||||
|
header = normalizeHeader(header);
|
||||||
|
|
||||||
|
if (header) {
|
||||||
|
const key = findKey(this, header);
|
||||||
|
|
||||||
|
return !!(key && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
},
|
||||||
|
|
||||||
|
delete: function(header, matcher) {
|
||||||
|
const self = this;
|
||||||
|
let deleted = false;
|
||||||
|
|
||||||
|
function deleteHeader(_header) {
|
||||||
|
_header = normalizeHeader(_header);
|
||||||
|
|
||||||
|
if (_header) {
|
||||||
|
const key = findKey(self, _header);
|
||||||
|
|
||||||
|
if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
|
||||||
|
delete self[key];
|
||||||
|
|
||||||
|
deleted = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (utils.isArray(header)) {
|
||||||
|
header.forEach(deleteHeader);
|
||||||
|
} else {
|
||||||
|
deleteHeader(header);
|
||||||
|
}
|
||||||
|
|
||||||
|
return deleted;
|
||||||
|
},
|
||||||
|
|
||||||
|
clear: function() {
|
||||||
|
return Object.keys(this).forEach(this.delete.bind(this));
|
||||||
|
},
|
||||||
|
|
||||||
|
normalize: function(format) {
|
||||||
|
const self = this;
|
||||||
|
const headers = {};
|
||||||
|
|
||||||
|
utils.forEach(this, (value, header) => {
|
||||||
|
const key = findKey(headers, header);
|
||||||
|
|
||||||
|
if (key) {
|
||||||
|
self[key] = normalizeValue(value);
|
||||||
|
delete self[header];
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const normalized = format ? formatHeader(header) : String(header).trim();
|
||||||
|
|
||||||
|
if (normalized !== header) {
|
||||||
|
delete self[header];
|
||||||
|
}
|
||||||
|
|
||||||
|
self[normalized] = normalizeValue(value);
|
||||||
|
|
||||||
|
headers[normalized] = true;
|
||||||
|
});
|
||||||
|
|
||||||
|
return this;
|
||||||
|
},
|
||||||
|
|
||||||
|
toJSON: function() {
|
||||||
|
const obj = Object.create(null);
|
||||||
|
|
||||||
|
utils.forEach(Object.assign({}, this[$defaults] || null, this),
|
||||||
|
(value, header) => {
|
||||||
|
if (value == null || value === false) return;
|
||||||
|
obj[header] = utils.isArray(value) ? value.join(', ') : value;
|
||||||
|
});
|
||||||
|
|
||||||
|
return obj;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Object.assign(AxiosHeaders, {
|
||||||
|
from: function(thing) {
|
||||||
|
if (utils.isString(thing)) {
|
||||||
|
return new this(parseHeaders(thing));
|
||||||
|
}
|
||||||
|
return thing instanceof this ? thing : new this(thing);
|
||||||
|
},
|
||||||
|
|
||||||
|
accessor: function(header) {
|
||||||
|
const internals = this[$internals] = (this[$internals] = {
|
||||||
|
accessors: {}
|
||||||
|
});
|
||||||
|
|
||||||
|
const accessors = internals.accessors;
|
||||||
|
const prototype = this.prototype;
|
||||||
|
|
||||||
|
function defineAccessor(_header) {
|
||||||
|
const lHeader = normalizeHeader(_header);
|
||||||
|
|
||||||
|
if (!accessors[lHeader]) {
|
||||||
|
buildAccessors(prototype, _header);
|
||||||
|
accessors[lHeader] = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
utils.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
|
||||||
|
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent']);
|
||||||
|
|
||||||
|
utils.freezeMethods(AxiosHeaders.prototype);
|
||||||
|
utils.freezeMethods(AxiosHeaders);
|
||||||
|
|
||||||
|
export default AxiosHeaders;
|
||||||
@@ -1,69 +1,71 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var utils = require('./../utils');
|
import utils from './../utils.js';
|
||||||
|
|
||||||
function InterceptorManager() {
|
class InterceptorManager {
|
||||||
this.handlers = [];
|
constructor() {
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Add a new interceptor to the stack
|
|
||||||
*
|
|
||||||
* @param {Function} fulfilled The function to handle `then` for a `Promise`
|
|
||||||
* @param {Function} rejected The function to handle `reject` for a `Promise`
|
|
||||||
*
|
|
||||||
* @return {Number} An ID used to remove interceptor later
|
|
||||||
*/
|
|
||||||
InterceptorManager.prototype.use = function use(fulfilled, rejected, options) {
|
|
||||||
this.handlers.push({
|
|
||||||
fulfilled: fulfilled,
|
|
||||||
rejected: rejected,
|
|
||||||
synchronous: options ? options.synchronous : false,
|
|
||||||
runWhen: options ? options.runWhen : null
|
|
||||||
});
|
|
||||||
return this.handlers.length - 1;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Remove an interceptor from the stack
|
|
||||||
*
|
|
||||||
* @param {Number} id The ID that was returned by `use`
|
|
||||||
*
|
|
||||||
* @returns {Boolean} `true` if the interceptor was removed, `false` otherwise
|
|
||||||
*/
|
|
||||||
InterceptorManager.prototype.eject = function eject(id) {
|
|
||||||
if (this.handlers[id]) {
|
|
||||||
this.handlers[id] = null;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Clear all interceptors from the stack
|
|
||||||
*
|
|
||||||
* @returns {void}
|
|
||||||
*/
|
|
||||||
InterceptorManager.prototype.clear = function clear() {
|
|
||||||
if (this.handlers) {
|
|
||||||
this.handlers = [];
|
this.handlers = [];
|
||||||
}
|
}
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Iterate over all the registered interceptors
|
* Add a new interceptor to the stack
|
||||||
*
|
*
|
||||||
* This method is particularly useful for skipping over any
|
* @param {Function} fulfilled The function to handle `then` for a `Promise`
|
||||||
* interceptors that may have become `null` calling `eject`.
|
* @param {Function} rejected The function to handle `reject` for a `Promise`
|
||||||
*
|
*
|
||||||
* @param {Function} fn The function to call for each interceptor
|
* @return {Number} An ID used to remove interceptor later
|
||||||
*
|
*/
|
||||||
* @returns {void}
|
use(fulfilled, rejected, options) {
|
||||||
*/
|
this.handlers.push({
|
||||||
InterceptorManager.prototype.forEach = function forEach(fn) {
|
fulfilled,
|
||||||
utils.forEach(this.handlers, function forEachHandler(h) {
|
rejected,
|
||||||
if (h !== null) {
|
synchronous: options ? options.synchronous : false,
|
||||||
fn(h);
|
runWhen: options ? options.runWhen : null
|
||||||
|
});
|
||||||
|
return this.handlers.length - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove an interceptor from the stack
|
||||||
|
*
|
||||||
|
* @param {Number} id The ID that was returned by `use`
|
||||||
|
*
|
||||||
|
* @returns {Boolean} `true` if the interceptor was removed, `false` otherwise
|
||||||
|
*/
|
||||||
|
eject(id) {
|
||||||
|
if (this.handlers[id]) {
|
||||||
|
this.handlers[id] = null;
|
||||||
}
|
}
|
||||||
});
|
}
|
||||||
};
|
|
||||||
|
|
||||||
module.exports = InterceptorManager;
|
/**
|
||||||
|
* Clear all interceptors from the stack
|
||||||
|
*
|
||||||
|
* @returns {void}
|
||||||
|
*/
|
||||||
|
clear() {
|
||||||
|
if (this.handlers) {
|
||||||
|
this.handlers = [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Iterate over all the registered interceptors
|
||||||
|
*
|
||||||
|
* This method is particularly useful for skipping over any
|
||||||
|
* interceptors that may have become `null` calling `eject`.
|
||||||
|
*
|
||||||
|
* @param {Function} fn The function to call for each interceptor
|
||||||
|
*
|
||||||
|
* @returns {void}
|
||||||
|
*/
|
||||||
|
forEach(fn) {
|
||||||
|
utils.forEach(this.handlers, function forEachHandler(h) {
|
||||||
|
if (h !== null) {
|
||||||
|
fn(h);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default InterceptorManager;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var isAbsoluteURL = require('../helpers/isAbsoluteURL');
|
import isAbsoluteURL from '../helpers/isAbsoluteURL.js';
|
||||||
var combineURLs = require('../helpers/combineURLs');
|
import combineURLs from '../helpers/combineURLs.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a new URL by combining the baseURL with the requestedURL,
|
* Creates a new URL by combining the baseURL with the requestedURL,
|
||||||
@@ -13,9 +13,9 @@ var combineURLs = require('../helpers/combineURLs');
|
|||||||
*
|
*
|
||||||
* @returns {string} The combined full path
|
* @returns {string} The combined full path
|
||||||
*/
|
*/
|
||||||
module.exports = function buildFullPath(baseURL, requestedURL) {
|
export default function buildFullPath(baseURL, requestedURL) {
|
||||||
if (baseURL && !isAbsoluteURL(requestedURL)) {
|
if (baseURL && !isAbsoluteURL(requestedURL)) {
|
||||||
return combineURLs(baseURL, requestedURL);
|
return combineURLs(baseURL, requestedURL);
|
||||||
}
|
}
|
||||||
return requestedURL;
|
return requestedURL;
|
||||||
};
|
}
|
||||||
|
|||||||
+16
-39
@@ -1,11 +1,10 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var utils = require('./../utils');
|
import transformData from './transformData.js';
|
||||||
var transformData = require('./transformData');
|
import isCancel from '../cancel/isCancel.js';
|
||||||
var isCancel = require('../cancel/isCancel');
|
import defaults from '../defaults/index.js';
|
||||||
var defaults = require('../defaults');
|
import CanceledError from '../cancel/CanceledError.js';
|
||||||
var CanceledError = require('../cancel/CanceledError');
|
import AxiosHeaders from '../core/AxiosHeaders.js';
|
||||||
var normalizeHeaderName = require('../helpers/normalizeHeaderName');
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Throws a `CanceledError` if cancellation has been requested.
|
* Throws a `CanceledError` if cancellation has been requested.
|
||||||
@@ -31,39 +30,18 @@ function throwIfCancellationRequested(config) {
|
|||||||
*
|
*
|
||||||
* @returns {Promise} The Promise to be fulfilled
|
* @returns {Promise} The Promise to be fulfilled
|
||||||
*/
|
*/
|
||||||
module.exports = function dispatchRequest(config) {
|
export default function dispatchRequest(config) {
|
||||||
throwIfCancellationRequested(config);
|
throwIfCancellationRequested(config);
|
||||||
|
|
||||||
// Ensure headers exist
|
config.headers = AxiosHeaders.from(config.headers);
|
||||||
config.headers = config.headers || {};
|
|
||||||
|
|
||||||
// Transform request data
|
// Transform request data
|
||||||
config.data = transformData.call(
|
config.data = transformData.call(
|
||||||
config,
|
config,
|
||||||
config.data,
|
|
||||||
config.headers,
|
|
||||||
null,
|
|
||||||
config.transformRequest
|
config.transformRequest
|
||||||
);
|
);
|
||||||
|
|
||||||
normalizeHeaderName(config.headers, 'Accept');
|
const adapter = config.adapter || defaults.adapter;
|
||||||
normalizeHeaderName(config.headers, 'Content-Type');
|
|
||||||
|
|
||||||
// Flatten headers
|
|
||||||
config.headers = utils.merge(
|
|
||||||
config.headers.common || {},
|
|
||||||
config.headers[config.method] || {},
|
|
||||||
config.headers
|
|
||||||
);
|
|
||||||
|
|
||||||
utils.forEach(
|
|
||||||
['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
|
|
||||||
function cleanHeaderConfig(method) {
|
|
||||||
delete config.headers[method];
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
var adapter = config.adapter || defaults.adapter;
|
|
||||||
|
|
||||||
return adapter(config).then(function onAdapterResolution(response) {
|
return adapter(config).then(function onAdapterResolution(response) {
|
||||||
throwIfCancellationRequested(config);
|
throwIfCancellationRequested(config);
|
||||||
@@ -71,12 +49,12 @@ module.exports = function dispatchRequest(config) {
|
|||||||
// Transform response data
|
// Transform response data
|
||||||
response.data = transformData.call(
|
response.data = transformData.call(
|
||||||
config,
|
config,
|
||||||
response.data,
|
config.transformResponse,
|
||||||
response.headers,
|
response
|
||||||
response.status,
|
|
||||||
config.transformResponse
|
|
||||||
);
|
);
|
||||||
|
|
||||||
|
response.headers = AxiosHeaders.from(response.headers);
|
||||||
|
|
||||||
return response;
|
return response;
|
||||||
}, function onAdapterRejection(reason) {
|
}, function onAdapterRejection(reason) {
|
||||||
if (!isCancel(reason)) {
|
if (!isCancel(reason)) {
|
||||||
@@ -86,14 +64,13 @@ module.exports = function dispatchRequest(config) {
|
|||||||
if (reason && reason.response) {
|
if (reason && reason.response) {
|
||||||
reason.response.data = transformData.call(
|
reason.response.data = transformData.call(
|
||||||
config,
|
config,
|
||||||
reason.response.data,
|
config.transformResponse,
|
||||||
reason.response.headers,
|
reason.response
|
||||||
reason.response.status,
|
|
||||||
config.transformResponse
|
|
||||||
);
|
);
|
||||||
|
reason.response.headers = AxiosHeaders.from(reason.response.headers);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return Promise.reject(reason);
|
return Promise.reject(reason);
|
||||||
});
|
});
|
||||||
};
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var utils = require('../utils');
|
import utils from '../utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Config-specific merge-function which creates a new config-object
|
* Config-specific merge-function which creates a new config-object
|
||||||
@@ -11,10 +11,10 @@ var utils = require('../utils');
|
|||||||
*
|
*
|
||||||
* @returns {Object} New object resulting from merging config2 to config1
|
* @returns {Object} New object resulting from merging config2 to config1
|
||||||
*/
|
*/
|
||||||
module.exports = function mergeConfig(config1, config2) {
|
export default function mergeConfig(config1, config2) {
|
||||||
// eslint-disable-next-line no-param-reassign
|
// eslint-disable-next-line no-param-reassign
|
||||||
config2 = config2 || {};
|
config2 = config2 || {};
|
||||||
var config = {};
|
const config = {};
|
||||||
|
|
||||||
function getMergedValue(target, source) {
|
function getMergedValue(target, source) {
|
||||||
if (utils.isPlainObject(target) && utils.isPlainObject(source)) {
|
if (utils.isPlainObject(target) && utils.isPlainObject(source)) {
|
||||||
@@ -61,7 +61,7 @@ module.exports = function mergeConfig(config1, config2) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var mergeMap = {
|
const mergeMap = {
|
||||||
'url': valueFromConfig2,
|
'url': valueFromConfig2,
|
||||||
'method': valueFromConfig2,
|
'method': valueFromConfig2,
|
||||||
'data': valueFromConfig2,
|
'data': valueFromConfig2,
|
||||||
@@ -92,10 +92,10 @@ module.exports = function mergeConfig(config1, config2) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) {
|
utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) {
|
||||||
var merge = mergeMap[prop] || mergeDeepProperties;
|
const merge = mergeMap[prop] || mergeDeepProperties;
|
||||||
var configValue = merge(prop);
|
const configValue = merge(prop);
|
||||||
(utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
|
(utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
|
||||||
});
|
});
|
||||||
|
|
||||||
return config;
|
return config;
|
||||||
};
|
}
|
||||||
|
|||||||
+4
-4
@@ -1,6 +1,6 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var AxiosError = require('./AxiosError');
|
import AxiosError from './AxiosError.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resolve or reject a Promise based on response status.
|
* Resolve or reject a Promise based on response status.
|
||||||
@@ -11,8 +11,8 @@ var AxiosError = require('./AxiosError');
|
|||||||
*
|
*
|
||||||
* @returns {object} The response.
|
* @returns {object} The response.
|
||||||
*/
|
*/
|
||||||
module.exports = function settle(resolve, reject, response) {
|
export default function settle(resolve, reject, response) {
|
||||||
var validateStatus = response.config.validateStatus;
|
const validateStatus = response.config.validateStatus;
|
||||||
if (!response.status || !validateStatus || validateStatus(response.status)) {
|
if (!response.status || !validateStatus || validateStatus(response.status)) {
|
||||||
resolve(response);
|
resolve(response);
|
||||||
} else {
|
} else {
|
||||||
@@ -24,4 +24,4 @@ module.exports = function settle(resolve, reject, response) {
|
|||||||
response
|
response
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|||||||
+14
-10
@@ -1,24 +1,28 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var utils = require('./../utils');
|
import utils from './../utils.js';
|
||||||
var defaults = require('../defaults');
|
import defaults from '../defaults/index.js';
|
||||||
|
import AxiosHeaders from '../core/AxiosHeaders.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Transform the data for a request or a response
|
* Transform the data for a request or a response
|
||||||
*
|
*
|
||||||
* @param {Object|String} data The data to be transformed
|
|
||||||
* @param {Array} headers The headers for the request or response
|
|
||||||
* @param {Number} status HTTP status code
|
|
||||||
* @param {Array|Function} fns A single function or Array of functions
|
* @param {Array|Function} fns A single function or Array of functions
|
||||||
|
* @param {?Object} response The response object
|
||||||
*
|
*
|
||||||
* @returns {*} The resulting transformed data
|
* @returns {*} The resulting transformed data
|
||||||
*/
|
*/
|
||||||
module.exports = function transformData(data, headers, status, fns) {
|
export default function transformData(fns, response) {
|
||||||
var context = this || defaults;
|
const config = this || defaults;
|
||||||
/*eslint no-param-reassign:0*/
|
const context = response || config;
|
||||||
|
const headers = AxiosHeaders.from(context.headers);
|
||||||
|
let data = context.data;
|
||||||
|
|
||||||
utils.forEach(fns, function transform(fn) {
|
utils.forEach(fns, function transform(fn) {
|
||||||
data = fn.call(context, data, headers, status);
|
data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
headers.normalize();
|
||||||
|
|
||||||
return data;
|
return data;
|
||||||
};
|
}
|
||||||
|
|||||||
+29
-48
@@ -1,34 +1,18 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var utils = require('../utils');
|
import utils from '../utils.js';
|
||||||
var normalizeHeaderName = require('../helpers/normalizeHeaderName');
|
import AxiosError from '../core/AxiosError.js';
|
||||||
var AxiosError = require('../core/AxiosError');
|
import transitionalDefaults from './transitional.js';
|
||||||
var transitionalDefaults = require('./transitional');
|
import toFormData from '../helpers/toFormData.js';
|
||||||
var toFormData = require('../helpers/toFormData');
|
import toURLEncodedForm from '../helpers/toURLEncodedForm.js';
|
||||||
var toURLEncodedForm = require('../helpers/toURLEncodedForm');
|
import platform from '../platform/index.js';
|
||||||
var platform = require('../platform');
|
import formDataToJSON from '../helpers/formDataToJSON.js';
|
||||||
var formDataToJSON = require('../helpers/formDataToJSON');
|
import adapters from '../adapters/index.js';
|
||||||
|
|
||||||
var DEFAULT_CONTENT_TYPE = {
|
const DEFAULT_CONTENT_TYPE = {
|
||||||
'Content-Type': 'application/x-www-form-urlencoded'
|
'Content-Type': 'application/x-www-form-urlencoded'
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* If the headers object is not undefined and the Content-Type property of the headers object
|
|
||||||
* is undefined, then set the Content-Type property of the headers object to the value passed
|
|
||||||
* in
|
|
||||||
*
|
|
||||||
* @param {Object<string, string>} headers - The headers object that will be sent to the server.
|
|
||||||
* @param {any} value - The value of the Content-Type header.
|
|
||||||
*
|
|
||||||
* @returns {void}
|
|
||||||
*/
|
|
||||||
function setContentTypeIfUnset(headers, value) {
|
|
||||||
if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
|
|
||||||
headers['Content-Type'] = value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* If the browser has an XMLHttpRequest object, use the XHR adapter, otherwise use the HTTP
|
* If the browser has an XMLHttpRequest object, use the XHR adapter, otherwise use the HTTP
|
||||||
* adapter
|
* adapter
|
||||||
@@ -36,13 +20,13 @@ function setContentTypeIfUnset(headers, value) {
|
|||||||
* @returns {Function}
|
* @returns {Function}
|
||||||
*/
|
*/
|
||||||
function getDefaultAdapter() {
|
function getDefaultAdapter() {
|
||||||
var adapter;
|
let adapter;
|
||||||
if (typeof XMLHttpRequest !== 'undefined') {
|
if (typeof XMLHttpRequest !== 'undefined') {
|
||||||
// For browsers use XHR adapter
|
// For browsers use XHR adapter
|
||||||
adapter = require('../adapters/xhr');
|
adapter = adapters.getAdapter('xhr');
|
||||||
} else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
|
} else if (typeof process !== 'undefined' && utils.kindOf(process) === 'process') {
|
||||||
// For node use HTTP adapter
|
// For node use HTTP adapter
|
||||||
adapter = require('../adapters/http');
|
adapter = adapters.getAdapter('http');
|
||||||
}
|
}
|
||||||
return adapter;
|
return adapter;
|
||||||
}
|
}
|
||||||
@@ -72,25 +56,22 @@ function stringifySafely(rawValue, parser, encoder) {
|
|||||||
return (encoder || JSON.stringify)(rawValue);
|
return (encoder || JSON.stringify)(rawValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
var defaults = {
|
const defaults = {
|
||||||
|
|
||||||
transitional: transitionalDefaults,
|
transitional: transitionalDefaults,
|
||||||
|
|
||||||
adapter: getDefaultAdapter(),
|
adapter: getDefaultAdapter(),
|
||||||
|
|
||||||
transformRequest: [function transformRequest(data, headers) {
|
transformRequest: [function transformRequest(data, headers) {
|
||||||
normalizeHeaderName(headers, 'Accept');
|
const contentType = headers.getContentType() || '';
|
||||||
normalizeHeaderName(headers, 'Content-Type');
|
const hasJSONContentType = contentType.indexOf('application/json') > -1;
|
||||||
|
const isObjectPayload = utils.isObject(data);
|
||||||
var contentType = headers && headers['Content-Type'] || '';
|
|
||||||
var hasJSONContentType = contentType.indexOf('application/json') > -1;
|
|
||||||
var isObjectPayload = utils.isObject(data);
|
|
||||||
|
|
||||||
if (isObjectPayload && utils.isHTMLForm(data)) {
|
if (isObjectPayload && utils.isHTMLForm(data)) {
|
||||||
data = new FormData(data);
|
data = new FormData(data);
|
||||||
}
|
}
|
||||||
|
|
||||||
var isFormData = utils.isFormData(data);
|
const isFormData = utils.isFormData(data);
|
||||||
|
|
||||||
if (isFormData) {
|
if (isFormData) {
|
||||||
if (!hasJSONContentType) {
|
if (!hasJSONContentType) {
|
||||||
@@ -111,19 +92,19 @@ var defaults = {
|
|||||||
return data.buffer;
|
return data.buffer;
|
||||||
}
|
}
|
||||||
if (utils.isURLSearchParams(data)) {
|
if (utils.isURLSearchParams(data)) {
|
||||||
setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
|
headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
|
||||||
return data.toString();
|
return data.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
var isFileList;
|
let isFileList;
|
||||||
|
|
||||||
if (isObjectPayload) {
|
if (isObjectPayload) {
|
||||||
if (contentType.indexOf('application/x-www-form-urlencoded') !== -1) {
|
if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
|
||||||
return toURLEncodedForm(data, this.formSerializer).toString();
|
return toURLEncodedForm(data, this.formSerializer).toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
if ((isFileList = utils.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {
|
if ((isFileList = utils.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {
|
||||||
var _FormData = this.env && this.env.FormData;
|
const _FormData = this.env && this.env.FormData;
|
||||||
|
|
||||||
return toFormData(
|
return toFormData(
|
||||||
isFileList ? {'files[]': data} : data,
|
isFileList ? {'files[]': data} : data,
|
||||||
@@ -134,7 +115,7 @@ var defaults = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (isObjectPayload || hasJSONContentType ) {
|
if (isObjectPayload || hasJSONContentType ) {
|
||||||
setContentTypeIfUnset(headers, 'application/json');
|
headers.setContentType('application/json', false);
|
||||||
return stringifySafely(data);
|
return stringifySafely(data);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -142,13 +123,13 @@ var defaults = {
|
|||||||
}],
|
}],
|
||||||
|
|
||||||
transformResponse: [function transformResponse(data) {
|
transformResponse: [function transformResponse(data) {
|
||||||
var transitional = this.transitional || defaults.transitional;
|
const transitional = this.transitional || defaults.transitional;
|
||||||
var forcedJSONParsing = transitional && transitional.forcedJSONParsing;
|
const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
|
||||||
var JSONRequested = this.responseType === 'json';
|
const JSONRequested = this.responseType === 'json';
|
||||||
|
|
||||||
if (data && utils.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {
|
if (data && utils.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {
|
||||||
var silentJSONParsing = transitional && transitional.silentJSONParsing;
|
const silentJSONParsing = transitional && transitional.silentJSONParsing;
|
||||||
var strictJSONParsing = !silentJSONParsing && JSONRequested;
|
const strictJSONParsing = !silentJSONParsing && JSONRequested;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return JSON.parse(data);
|
return JSON.parse(data);
|
||||||
@@ -201,4 +182,4 @@ utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
|
|||||||
defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
|
defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
|
||||||
});
|
});
|
||||||
|
|
||||||
module.exports = defaults;
|
export default defaults;
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
module.exports = {
|
export default {
|
||||||
silentJSONParsing: true,
|
silentJSONParsing: true,
|
||||||
forcedJSONParsing: true,
|
forcedJSONParsing: true,
|
||||||
clarifyTimeoutError: false
|
clarifyTimeoutError: false
|
||||||
|
|||||||
Vendored
+2
-2
@@ -1,2 +1,2 @@
|
|||||||
// eslint-disable-next-line strict
|
import FormData from 'form-data';
|
||||||
module.exports = require('form-data');
|
export default FormData;
|
||||||
|
|||||||
Vendored
+1
-3
@@ -1,3 +1 @@
|
|||||||
module.exports = {
|
export const VERSION = "1.0.0-alpha.1";
|
||||||
"version": "1.0.0-alpha.1"
|
|
||||||
};
|
|
||||||
@@ -0,0 +1,191 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
import stream from 'stream';
|
||||||
|
import utils from '../utils.js';
|
||||||
|
import throttle from './throttle.js';
|
||||||
|
import speedometer from './speedometer.js';
|
||||||
|
|
||||||
|
const kInternals = Symbol('internals');
|
||||||
|
|
||||||
|
class AxiosTransformStream extends stream.Transform{
|
||||||
|
constructor(options) {
|
||||||
|
options = utils.toFlatObject(options, {
|
||||||
|
maxRate: 0,
|
||||||
|
chunkSize: 64 * 1024,
|
||||||
|
minChunkSize: 100,
|
||||||
|
timeWindow: 500,
|
||||||
|
ticksRate: 2,
|
||||||
|
samplesCount: 15
|
||||||
|
}, null, (prop, source) => {
|
||||||
|
return !utils.isUndefined(source[prop]);
|
||||||
|
});
|
||||||
|
|
||||||
|
super({
|
||||||
|
readableHighWaterMark: options.chunkSize
|
||||||
|
});
|
||||||
|
|
||||||
|
const self = this;
|
||||||
|
|
||||||
|
const internals = this[kInternals] = {
|
||||||
|
length: options.length,
|
||||||
|
timeWindow: options.timeWindow,
|
||||||
|
ticksRate: options.ticksRate,
|
||||||
|
chunkSize: options.chunkSize,
|
||||||
|
maxRate: options.maxRate,
|
||||||
|
minChunkSize: options.minChunkSize,
|
||||||
|
bytesSeen: 0,
|
||||||
|
isCaptured: false,
|
||||||
|
notifiedBytesLoaded: 0,
|
||||||
|
ts: Date.now(),
|
||||||
|
bytes: 0,
|
||||||
|
onReadCallback: null
|
||||||
|
};
|
||||||
|
|
||||||
|
const _speedometer = speedometer(internals.ticksRate * options.samplesCount, internals.timeWindow);
|
||||||
|
|
||||||
|
this.on('newListener', event => {
|
||||||
|
if (event === 'progress') {
|
||||||
|
if (!internals.isCaptured) {
|
||||||
|
internals.isCaptured = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let bytesNotified = 0;
|
||||||
|
|
||||||
|
internals.updateProgress = throttle(function throttledHandler() {
|
||||||
|
const totalBytes = internals.length;
|
||||||
|
const bytesTransferred = internals.bytesSeen;
|
||||||
|
const progressBytes = bytesTransferred - bytesNotified;
|
||||||
|
if (!progressBytes || self.destroyed) return;
|
||||||
|
|
||||||
|
const rate = _speedometer(progressBytes);
|
||||||
|
|
||||||
|
bytesNotified = bytesTransferred;
|
||||||
|
|
||||||
|
process.nextTick(() => {
|
||||||
|
self.emit('progress', {
|
||||||
|
'loaded': bytesTransferred,
|
||||||
|
'total': totalBytes,
|
||||||
|
'progress': totalBytes ? (bytesTransferred / totalBytes) : undefined,
|
||||||
|
'bytes': progressBytes,
|
||||||
|
'rate': rate ? rate : undefined,
|
||||||
|
'estimated': rate && totalBytes && bytesTransferred <= totalBytes ?
|
||||||
|
(totalBytes - bytesTransferred) / rate : undefined
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}, internals.ticksRate);
|
||||||
|
|
||||||
|
const onFinish = () => {
|
||||||
|
internals.updateProgress(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
this.once('end', onFinish);
|
||||||
|
this.once('error', onFinish);
|
||||||
|
}
|
||||||
|
|
||||||
|
_read(size) {
|
||||||
|
const internals = this[kInternals];
|
||||||
|
|
||||||
|
if (internals.onReadCallback) {
|
||||||
|
internals.onReadCallback();
|
||||||
|
}
|
||||||
|
|
||||||
|
return super._read(size);
|
||||||
|
}
|
||||||
|
|
||||||
|
_transform(chunk, encoding, callback) {
|
||||||
|
const self = this;
|
||||||
|
const internals = this[kInternals];
|
||||||
|
const maxRate = internals.maxRate;
|
||||||
|
|
||||||
|
const readableHighWaterMark = this.readableHighWaterMark;
|
||||||
|
|
||||||
|
const timeWindow = internals.timeWindow;
|
||||||
|
|
||||||
|
const divider = 1000 / timeWindow;
|
||||||
|
const bytesThreshold = (maxRate / divider);
|
||||||
|
const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0;
|
||||||
|
|
||||||
|
function pushChunk(_chunk, _callback) {
|
||||||
|
const bytes = Buffer.byteLength(_chunk);
|
||||||
|
internals.bytesSeen += bytes;
|
||||||
|
internals.bytes += bytes;
|
||||||
|
|
||||||
|
if (internals.isCaptured) {
|
||||||
|
internals.updateProgress();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (self.push(_chunk)) {
|
||||||
|
process.nextTick(_callback);
|
||||||
|
} else {
|
||||||
|
internals.onReadCallback = () => {
|
||||||
|
internals.onReadCallback = null;
|
||||||
|
process.nextTick(_callback);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const transformChunk = (_chunk, _callback) => {
|
||||||
|
const chunkSize = Buffer.byteLength(_chunk);
|
||||||
|
let chunkRemainder = null;
|
||||||
|
let maxChunkSize = readableHighWaterMark;
|
||||||
|
let bytesLeft;
|
||||||
|
let passed = 0;
|
||||||
|
|
||||||
|
if (maxRate) {
|
||||||
|
const now = Date.now();
|
||||||
|
|
||||||
|
if (!internals.ts || (passed = (now - internals.ts)) >= timeWindow) {
|
||||||
|
internals.ts = now;
|
||||||
|
bytesLeft = bytesThreshold - internals.bytes;
|
||||||
|
internals.bytes = bytesLeft < 0 ? -bytesLeft : 0;
|
||||||
|
passed = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
bytesLeft = bytesThreshold - internals.bytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (maxRate) {
|
||||||
|
if (bytesLeft <= 0) {
|
||||||
|
// next time window
|
||||||
|
return setTimeout(() => {
|
||||||
|
_callback(null, _chunk);
|
||||||
|
}, timeWindow - passed);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (bytesLeft < maxChunkSize) {
|
||||||
|
maxChunkSize = bytesLeft;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (maxChunkSize && chunkSize > maxChunkSize && (chunkSize - maxChunkSize) > minChunkSize) {
|
||||||
|
chunkRemainder = _chunk.subarray(maxChunkSize);
|
||||||
|
_chunk = _chunk.subarray(0, maxChunkSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
pushChunk(_chunk, chunkRemainder ? () => {
|
||||||
|
process.nextTick(_callback, null, chunkRemainder);
|
||||||
|
} : _callback);
|
||||||
|
};
|
||||||
|
|
||||||
|
transformChunk(chunk, function transformNextChunk(err, _chunk) {
|
||||||
|
if (err) {
|
||||||
|
return callback(err);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_chunk) {
|
||||||
|
transformChunk(_chunk, transformNextChunk);
|
||||||
|
} else {
|
||||||
|
callback(null);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
setLength(length) {
|
||||||
|
this[kInternals].length = +length;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default AxiosTransformStream;
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var toFormData = require('./toFormData');
|
import toFormData from './toFormData.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* It encodes a string by replacing all characters that are not in the unreserved set with
|
* It encodes a string by replacing all characters that are not in the unreserved set with
|
||||||
@@ -11,7 +11,7 @@ var toFormData = require('./toFormData');
|
|||||||
* @returns {string} The encoded string.
|
* @returns {string} The encoded string.
|
||||||
*/
|
*/
|
||||||
function encode(str) {
|
function encode(str) {
|
||||||
var charMap = {
|
const charMap = {
|
||||||
'!': '%21',
|
'!': '%21',
|
||||||
"'": '%27',
|
"'": '%27',
|
||||||
'(': '%28',
|
'(': '%28',
|
||||||
@@ -20,7 +20,7 @@ function encode(str) {
|
|||||||
'%20': '+',
|
'%20': '+',
|
||||||
'%00': '\x00'
|
'%00': '\x00'
|
||||||
};
|
};
|
||||||
return encodeURIComponent(str).replace(/[!'\(\)~]|%20|%00/g, function replacer(match) {
|
return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
|
||||||
return charMap[match];
|
return charMap[match];
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -39,14 +39,14 @@ function AxiosURLSearchParams(params, options) {
|
|||||||
params && toFormData(params, this, options);
|
params && toFormData(params, this, options);
|
||||||
}
|
}
|
||||||
|
|
||||||
var prototype = AxiosURLSearchParams.prototype;
|
const prototype = AxiosURLSearchParams.prototype;
|
||||||
|
|
||||||
prototype.append = function append(name, value) {
|
prototype.append = function append(name, value) {
|
||||||
this._pairs.push([name, value]);
|
this._pairs.push([name, value]);
|
||||||
};
|
};
|
||||||
|
|
||||||
prototype.toString = function toString(encoder) {
|
prototype.toString = function toString(encoder) {
|
||||||
var _encode = encoder ? function(value) {
|
const _encode = encoder ? function(value) {
|
||||||
return encoder.call(this, value, encode);
|
return encoder.call(this, value, encode);
|
||||||
} : encode;
|
} : encode;
|
||||||
|
|
||||||
@@ -55,4 +55,4 @@ prototype.toString = function toString(encoder) {
|
|||||||
}, '').join('&');
|
}, '').join('&');
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = AxiosURLSearchParams;
|
export default AxiosURLSearchParams;
|
||||||
|
|||||||
+2
-2
@@ -1,7 +1,7 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
module.exports = function bind(fn, thisArg) {
|
export default function bind(fn, thisArg) {
|
||||||
return function wrap() {
|
return function wrap() {
|
||||||
return fn.apply(thisArg, arguments);
|
return fn.apply(thisArg, arguments);
|
||||||
};
|
};
|
||||||
};
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var utils = require('../utils');
|
import utils from '../utils.js';
|
||||||
var AxiosURLSearchParams = require('../helpers/AxiosURLSearchParams');
|
import AxiosURLSearchParams from '../helpers/AxiosURLSearchParams.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their
|
* It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their
|
||||||
@@ -30,21 +30,21 @@ function encode(val) {
|
|||||||
*
|
*
|
||||||
* @returns {string} The formatted url
|
* @returns {string} The formatted url
|
||||||
*/
|
*/
|
||||||
module.exports = function buildURL(url, params, options) {
|
export default function buildURL(url, params, options) {
|
||||||
/*eslint no-param-reassign:0*/
|
/*eslint no-param-reassign:0*/
|
||||||
if (!params) {
|
if (!params) {
|
||||||
return url;
|
return url;
|
||||||
}
|
}
|
||||||
|
|
||||||
var hashmarkIndex = url.indexOf('#');
|
const hashmarkIndex = url.indexOf('#');
|
||||||
|
|
||||||
if (hashmarkIndex !== -1) {
|
if (hashmarkIndex !== -1) {
|
||||||
url = url.slice(0, hashmarkIndex);
|
url = url.slice(0, hashmarkIndex);
|
||||||
}
|
}
|
||||||
|
|
||||||
var _encode = options && options.encode || encode;
|
const _encode = options && options.encode || encode;
|
||||||
|
|
||||||
var serializerParams = utils.isURLSearchParams(params) ?
|
const serializerParams = utils.isURLSearchParams(params) ?
|
||||||
params.toString() :
|
params.toString() :
|
||||||
new AxiosURLSearchParams(params, options).toString(_encode);
|
new AxiosURLSearchParams(params, options).toString(_encode);
|
||||||
|
|
||||||
@@ -53,4 +53,4 @@ module.exports = function buildURL(url, params, options) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return url;
|
return url;
|
||||||
};
|
}
|
||||||
|
|||||||
@@ -8,8 +8,8 @@
|
|||||||
*
|
*
|
||||||
* @returns {string} The combined URL
|
* @returns {string} The combined URL
|
||||||
*/
|
*/
|
||||||
module.exports = function combineURLs(baseURL, relativeURL) {
|
export default function combineURLs(baseURL, relativeURL) {
|
||||||
return relativeURL
|
return relativeURL
|
||||||
? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
|
? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
|
||||||
: baseURL;
|
: baseURL;
|
||||||
};
|
}
|
||||||
|
|||||||
+44
-46
@@ -1,53 +1,51 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var utils = require('./../utils');
|
import utils from './../utils.js';
|
||||||
|
|
||||||
module.exports = (
|
export default utils.isStandardBrowserEnv() ?
|
||||||
utils.isStandardBrowserEnv() ?
|
|
||||||
|
|
||||||
// Standard browser envs support document.cookie
|
// Standard browser envs support document.cookie
|
||||||
(function standardBrowserEnv() {
|
(function standardBrowserEnv() {
|
||||||
return {
|
return {
|
||||||
write: function write(name, value, expires, path, domain, secure) {
|
write: function write(name, value, expires, path, domain, secure) {
|
||||||
var cookie = [];
|
const cookie = [];
|
||||||
cookie.push(name + '=' + encodeURIComponent(value));
|
cookie.push(name + '=' + encodeURIComponent(value));
|
||||||
|
|
||||||
if (utils.isNumber(expires)) {
|
if (utils.isNumber(expires)) {
|
||||||
cookie.push('expires=' + new Date(expires).toGMTString());
|
cookie.push('expires=' + new Date(expires).toGMTString());
|
||||||
}
|
|
||||||
|
|
||||||
if (utils.isString(path)) {
|
|
||||||
cookie.push('path=' + path);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (utils.isString(domain)) {
|
|
||||||
cookie.push('domain=' + domain);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (secure === true) {
|
|
||||||
cookie.push('secure');
|
|
||||||
}
|
|
||||||
|
|
||||||
document.cookie = cookie.join('; ');
|
|
||||||
},
|
|
||||||
|
|
||||||
read: function read(name) {
|
|
||||||
var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
|
|
||||||
return (match ? decodeURIComponent(match[3]) : null);
|
|
||||||
},
|
|
||||||
|
|
||||||
remove: function remove(name) {
|
|
||||||
this.write(name, '', Date.now() - 86400000);
|
|
||||||
}
|
}
|
||||||
};
|
|
||||||
})() :
|
|
||||||
|
|
||||||
// Non standard browser env (web workers, react-native) lack needed support.
|
if (utils.isString(path)) {
|
||||||
(function nonStandardBrowserEnv() {
|
cookie.push('path=' + path);
|
||||||
return {
|
}
|
||||||
write: function write() {},
|
|
||||||
read: function read() { return null; },
|
if (utils.isString(domain)) {
|
||||||
remove: function remove() {}
|
cookie.push('domain=' + domain);
|
||||||
};
|
}
|
||||||
})()
|
|
||||||
);
|
if (secure === true) {
|
||||||
|
cookie.push('secure');
|
||||||
|
}
|
||||||
|
|
||||||
|
document.cookie = cookie.join('; ');
|
||||||
|
},
|
||||||
|
|
||||||
|
read: function read(name) {
|
||||||
|
const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
|
||||||
|
return (match ? decodeURIComponent(match[3]) : null);
|
||||||
|
},
|
||||||
|
|
||||||
|
remove: function remove(name) {
|
||||||
|
this.write(name, '', Date.now() - 86400000);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
})() :
|
||||||
|
|
||||||
|
// Non standard browser env (web workers, react-native) lack needed support.
|
||||||
|
(function nonStandardBrowserEnv() {
|
||||||
|
return {
|
||||||
|
write: function write() {},
|
||||||
|
read: function read() { return null; },
|
||||||
|
remove: function remove() {}
|
||||||
|
};
|
||||||
|
})();
|
||||||
|
|||||||
@@ -12,7 +12,7 @@
|
|||||||
*
|
*
|
||||||
* @returns {void}
|
* @returns {void}
|
||||||
*/
|
*/
|
||||||
module.exports = function deprecatedMethod(method, instead, docs) {
|
export default function deprecatedMethod(method, instead, docs) {
|
||||||
try {
|
try {
|
||||||
console.warn(
|
console.warn(
|
||||||
'DEPRECATED method `' + method + '`.' +
|
'DEPRECATED method `' + method + '`.' +
|
||||||
@@ -23,4 +23,4 @@ module.exports = function deprecatedMethod(method, instead, docs) {
|
|||||||
console.warn('For more information about usage see ' + docs);
|
console.warn('For more information about usage see ' + docs);
|
||||||
}
|
}
|
||||||
} catch (e) { /* Ignore */ }
|
} catch (e) { /* Ignore */ }
|
||||||
};
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var utils = require('../utils');
|
import utils from '../utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
|
* It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
|
||||||
@@ -14,7 +14,7 @@ function parsePropPath(name) {
|
|||||||
// foo.x.y.z
|
// foo.x.y.z
|
||||||
// foo-x-y-z
|
// foo-x-y-z
|
||||||
// foo x y z
|
// foo x y z
|
||||||
return utils.matchAll(/\w+|\[(\w*)]/g, name).map(function(match) {
|
return utils.matchAll(/\w+|\[(\w*)]/g, name).map(match => {
|
||||||
return match[0] === '[]' ? '' : match[1] || match[0];
|
return match[0] === '[]' ? '' : match[1] || match[0];
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -27,11 +27,11 @@ function parsePropPath(name) {
|
|||||||
* @returns An object with the same keys and values as the array.
|
* @returns An object with the same keys and values as the array.
|
||||||
*/
|
*/
|
||||||
function arrayToObject(arr) {
|
function arrayToObject(arr) {
|
||||||
var obj = {};
|
const obj = {};
|
||||||
var keys = Object.keys(arr);
|
const keys = Object.keys(arr);
|
||||||
var i;
|
let i;
|
||||||
var len = keys.length;
|
const len = keys.length;
|
||||||
var key;
|
let key;
|
||||||
for (i = 0; i < len; i++) {
|
for (i = 0; i < len; i++) {
|
||||||
key = keys[i];
|
key = keys[i];
|
||||||
obj[key] = arr[key];
|
obj[key] = arr[key];
|
||||||
@@ -48,13 +48,13 @@ function arrayToObject(arr) {
|
|||||||
*/
|
*/
|
||||||
function formDataToJSON(formData) {
|
function formDataToJSON(formData) {
|
||||||
function buildPath(path, value, target, index) {
|
function buildPath(path, value, target, index) {
|
||||||
var name = path[index++];
|
let name = path[index++];
|
||||||
var isNumericKey = Number.isFinite(+name);
|
const isNumericKey = Number.isFinite(+name);
|
||||||
var isLast = index >= path.length;
|
const isLast = index >= path.length;
|
||||||
name = !name && utils.isArray(target) ? target.length : name;
|
name = !name && utils.isArray(target) ? target.length : name;
|
||||||
|
|
||||||
if (isLast) {
|
if (isLast) {
|
||||||
if (utils.hasOwnProperty(target, name)) {
|
if (utils.hasOwnProp(target, name)) {
|
||||||
target[name] = [target[name], value];
|
target[name] = [target[name], value];
|
||||||
} else {
|
} else {
|
||||||
target[name] = value;
|
target[name] = value;
|
||||||
@@ -67,7 +67,7 @@ function formDataToJSON(formData) {
|
|||||||
target[name] = [];
|
target[name] = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
var result = buildPath(path, value, target[name], index);
|
const result = buildPath(path, value, target[name], index);
|
||||||
|
|
||||||
if (result && utils.isArray(target[name])) {
|
if (result && utils.isArray(target[name])) {
|
||||||
target[name] = arrayToObject(target[name]);
|
target[name] = arrayToObject(target[name]);
|
||||||
@@ -77,9 +77,9 @@ function formDataToJSON(formData) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (utils.isFormData(formData) && utils.isFunction(formData.entries)) {
|
if (utils.isFormData(formData) && utils.isFunction(formData.entries)) {
|
||||||
var obj = {};
|
const obj = {};
|
||||||
|
|
||||||
utils.forEachEntry(formData, function(name, value) {
|
utils.forEachEntry(formData, (name, value) => {
|
||||||
buildPath(parsePropPath(name), value, obj, 0);
|
buildPath(parsePropPath(name), value, obj, 0);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -89,4 +89,4 @@ function formDataToJSON(formData) {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = formDataToJSON;
|
export default formDataToJSON;
|
||||||
|
|||||||
+13
-13
@@ -1,10 +1,10 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var AxiosError = require('../core/AxiosError');
|
import AxiosError from '../core/AxiosError.js';
|
||||||
var parseProtocol = require('./parseProtocol');
|
import parseProtocol from './parseProtocol.js';
|
||||||
var platform = require('../platform');
|
import platform from '../platform/index.js';
|
||||||
|
|
||||||
var DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;
|
const DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Parse data uri to a Buffer or Blob
|
* Parse data uri to a Buffer or Blob
|
||||||
@@ -16,9 +16,9 @@ var DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;
|
|||||||
*
|
*
|
||||||
* @returns {Buffer|Blob}
|
* @returns {Buffer|Blob}
|
||||||
*/
|
*/
|
||||||
module.exports = function fromDataURI(uri, asBlob, options) {
|
export default function fromDataURI(uri, asBlob, options) {
|
||||||
var _Blob = options && options.Blob || platform.classes.Blob;
|
const _Blob = options && options.Blob || platform.classes.Blob;
|
||||||
var protocol = parseProtocol(uri);
|
const protocol = parseProtocol(uri);
|
||||||
|
|
||||||
if (asBlob === undefined && _Blob) {
|
if (asBlob === undefined && _Blob) {
|
||||||
asBlob = true;
|
asBlob = true;
|
||||||
@@ -27,16 +27,16 @@ module.exports = function fromDataURI(uri, asBlob, options) {
|
|||||||
if (protocol === 'data') {
|
if (protocol === 'data') {
|
||||||
uri = protocol.length ? uri.slice(protocol.length + 1) : uri;
|
uri = protocol.length ? uri.slice(protocol.length + 1) : uri;
|
||||||
|
|
||||||
var match = DATA_URL_PATTERN.exec(uri);
|
const match = DATA_URL_PATTERN.exec(uri);
|
||||||
|
|
||||||
if (!match) {
|
if (!match) {
|
||||||
throw new AxiosError('Invalid URL', AxiosError.ERR_INVALID_URL);
|
throw new AxiosError('Invalid URL', AxiosError.ERR_INVALID_URL);
|
||||||
}
|
}
|
||||||
|
|
||||||
var mime = match[1];
|
const mime = match[1];
|
||||||
var isBase64 = match[2];
|
const isBase64 = match[2];
|
||||||
var body = match[3];
|
const body = match[3];
|
||||||
var buffer = Buffer.from(decodeURIComponent(body), isBase64 ? 'base64' : 'utf8');
|
const buffer = Buffer.from(decodeURIComponent(body), isBase64 ? 'base64' : 'utf8');
|
||||||
|
|
||||||
if (asBlob) {
|
if (asBlob) {
|
||||||
if (!_Blob) {
|
if (!_Blob) {
|
||||||
@@ -50,4 +50,4 @@ module.exports = function fromDataURI(uri, asBlob, options) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
throw new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_NOT_SUPPORT);
|
throw new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_NOT_SUPPORT);
|
||||||
};
|
}
|
||||||
|
|||||||
@@ -7,9 +7,9 @@
|
|||||||
*
|
*
|
||||||
* @returns {boolean} True if the specified URL is absolute, otherwise false
|
* @returns {boolean} True if the specified URL is absolute, otherwise false
|
||||||
*/
|
*/
|
||||||
module.exports = function isAbsoluteURL(url) {
|
export default function isAbsoluteURL(url) {
|
||||||
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
|
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
|
||||||
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
|
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
|
||||||
// by any combination of letters, digits, plus, period, or hyphen.
|
// by any combination of letters, digits, plus, period, or hyphen.
|
||||||
return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
|
return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
|
||||||
};
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var utils = require('./../utils');
|
import utils from './../utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Determines whether the payload is an error thrown by Axios
|
* Determines whether the payload is an error thrown by Axios
|
||||||
@@ -9,6 +9,6 @@ var utils = require('./../utils');
|
|||||||
*
|
*
|
||||||
* @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
|
* @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
|
||||||
*/
|
*/
|
||||||
module.exports = function isAxiosError(payload) {
|
export default function isAxiosError(payload) {
|
||||||
return utils.isObject(payload) && (payload.isAxiosError === true);
|
return utils.isObject(payload) && (payload.isAxiosError === true);
|
||||||
};
|
}
|
||||||
|
|||||||
@@ -1,68 +1,66 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var utils = require('./../utils');
|
import utils from './../utils.js';
|
||||||
|
|
||||||
module.exports = (
|
export default utils.isStandardBrowserEnv() ?
|
||||||
utils.isStandardBrowserEnv() ?
|
|
||||||
|
|
||||||
// Standard browser envs have full support of the APIs needed to test
|
// Standard browser envs have full support of the APIs needed to test
|
||||||
// whether the request URL is of the same origin as current location.
|
// whether the request URL is of the same origin as current location.
|
||||||
(function standardBrowserEnv() {
|
(function standardBrowserEnv() {
|
||||||
var msie = /(msie|trident)/i.test(navigator.userAgent);
|
const msie = /(msie|trident)/i.test(navigator.userAgent);
|
||||||
var urlParsingNode = document.createElement('a');
|
const urlParsingNode = document.createElement('a');
|
||||||
var originURL;
|
let originURL;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Parse a URL to discover it's components
|
* Parse a URL to discover it's components
|
||||||
*
|
*
|
||||||
* @param {String} url The URL to be parsed
|
* @param {String} url The URL to be parsed
|
||||||
* @returns {Object}
|
* @returns {Object}
|
||||||
*/
|
*/
|
||||||
function resolveURL(url) {
|
function resolveURL(url) {
|
||||||
var href = url;
|
let href = url;
|
||||||
|
|
||||||
if (msie) {
|
|
||||||
// IE needs attribute set twice to normalize properties
|
|
||||||
urlParsingNode.setAttribute('href', href);
|
|
||||||
href = urlParsingNode.href;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
if (msie) {
|
||||||
|
// IE needs attribute set twice to normalize properties
|
||||||
urlParsingNode.setAttribute('href', href);
|
urlParsingNode.setAttribute('href', href);
|
||||||
|
href = urlParsingNode.href;
|
||||||
// urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
|
|
||||||
return {
|
|
||||||
href: urlParsingNode.href,
|
|
||||||
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
|
|
||||||
host: urlParsingNode.host,
|
|
||||||
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
|
|
||||||
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
|
|
||||||
hostname: urlParsingNode.hostname,
|
|
||||||
port: urlParsingNode.port,
|
|
||||||
pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
|
|
||||||
urlParsingNode.pathname :
|
|
||||||
'/' + urlParsingNode.pathname
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
originURL = resolveURL(window.location.href);
|
urlParsingNode.setAttribute('href', href);
|
||||||
|
|
||||||
/**
|
// urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
|
||||||
* Determine if a URL shares the same origin as the current location
|
return {
|
||||||
*
|
href: urlParsingNode.href,
|
||||||
* @param {String} requestURL The URL to test
|
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
|
||||||
* @returns {boolean} True if URL shares the same origin, otherwise false
|
host: urlParsingNode.host,
|
||||||
*/
|
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
|
||||||
return function isURLSameOrigin(requestURL) {
|
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
|
||||||
var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
|
hostname: urlParsingNode.hostname,
|
||||||
return (parsed.protocol === originURL.protocol &&
|
port: urlParsingNode.port,
|
||||||
parsed.host === originURL.host);
|
pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
|
||||||
|
urlParsingNode.pathname :
|
||||||
|
'/' + urlParsingNode.pathname
|
||||||
};
|
};
|
||||||
})() :
|
}
|
||||||
|
|
||||||
// Non standard browser envs (web workers, react-native) lack needed support.
|
originURL = resolveURL(window.location.href);
|
||||||
(function nonStandardBrowserEnv() {
|
|
||||||
return function isURLSameOrigin() {
|
/**
|
||||||
return true;
|
* Determine if a URL shares the same origin as the current location
|
||||||
};
|
*
|
||||||
})()
|
* @param {String} requestURL The URL to test
|
||||||
);
|
* @returns {boolean} True if URL shares the same origin, otherwise false
|
||||||
|
*/
|
||||||
|
return function isURLSameOrigin(requestURL) {
|
||||||
|
const parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
|
||||||
|
return (parsed.protocol === originURL.protocol &&
|
||||||
|
parsed.host === originURL.host);
|
||||||
|
};
|
||||||
|
})() :
|
||||||
|
|
||||||
|
// Non standard browser envs (web workers, react-native) lack needed support.
|
||||||
|
(function nonStandardBrowserEnv() {
|
||||||
|
return function isURLSameOrigin() {
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
})();
|
||||||
|
|||||||
@@ -1,12 +0,0 @@
|
|||||||
'use strict';
|
|
||||||
|
|
||||||
var utils = require('../utils');
|
|
||||||
|
|
||||||
module.exports = function normalizeHeaderName(headers, normalizedName) {
|
|
||||||
utils.forEach(headers, function processHeader(value, name) {
|
|
||||||
if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
|
|
||||||
headers[normalizedName] = value;
|
|
||||||
delete headers[name];
|
|
||||||
}
|
|
||||||
});
|
|
||||||
};
|
|
||||||
+1
-1
@@ -1,2 +1,2 @@
|
|||||||
// eslint-disable-next-line strict
|
// eslint-disable-next-line strict
|
||||||
module.exports = null;
|
export default null;
|
||||||
|
|||||||
+23
-22
@@ -1,15 +1,15 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var utils = require('./../utils');
|
import utils from './../utils.js';
|
||||||
|
|
||||||
// Headers whose duplicates are ignored by node
|
// RawAxiosHeaders whose duplicates are ignored by node
|
||||||
// c.f. https://nodejs.org/api/http.html#http_message_headers
|
// c.f. https://nodejs.org/api/http.html#http_message_headers
|
||||||
var ignoreDuplicateOf = [
|
const ignoreDuplicateOf = utils.toObjectSet([
|
||||||
'age', 'authorization', 'content-length', 'content-type', 'etag',
|
'age', 'authorization', 'content-length', 'content-type', 'etag',
|
||||||
'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
|
'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
|
||||||
'last-modified', 'location', 'max-forwards', 'proxy-authorization',
|
'last-modified', 'location', 'max-forwards', 'proxy-authorization',
|
||||||
'referer', 'retry-after', 'user-agent'
|
'referer', 'retry-after', 'user-agent'
|
||||||
];
|
]);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Parse headers into an object
|
* Parse headers into an object
|
||||||
@@ -21,32 +21,33 @@ var ignoreDuplicateOf = [
|
|||||||
* Transfer-Encoding: chunked
|
* Transfer-Encoding: chunked
|
||||||
* ```
|
* ```
|
||||||
*
|
*
|
||||||
* @param {String} headers Headers needing to be parsed
|
* @param {String} rawHeaders Headers needing to be parsed
|
||||||
*
|
*
|
||||||
* @returns {Object} Headers parsed into an object
|
* @returns {Object} Headers parsed into an object
|
||||||
*/
|
*/
|
||||||
module.exports = function parseHeaders(headers) {
|
export default rawHeaders => {
|
||||||
var parsed = {};
|
const parsed = {};
|
||||||
var key;
|
let key;
|
||||||
var val;
|
let val;
|
||||||
var i;
|
let i;
|
||||||
|
|
||||||
if (!headers) { return parsed; }
|
rawHeaders && rawHeaders.split('\n').forEach(function parser(line) {
|
||||||
|
|
||||||
utils.forEach(headers.split('\n'), function parser(line) {
|
|
||||||
i = line.indexOf(':');
|
i = line.indexOf(':');
|
||||||
key = utils.trim(line.slice(0, i)).toLowerCase();
|
key = line.substring(0, i).trim().toLowerCase();
|
||||||
val = utils.trim(line.slice(i + 1));
|
val = line.substring(i + 1).trim();
|
||||||
|
|
||||||
if (key) {
|
if (!key || (parsed[key] && ignoreDuplicateOf[key])) {
|
||||||
if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
|
return;
|
||||||
return;
|
}
|
||||||
}
|
|
||||||
if (key === 'set-cookie') {
|
if (key === 'set-cookie') {
|
||||||
parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
|
if (parsed[key]) {
|
||||||
|
parsed[key].push(val);
|
||||||
} else {
|
} else {
|
||||||
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
|
parsed[key] = [val];
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
module.exports = function parseProtocol(url) {
|
export default function parseProtocol(url) {
|
||||||
var match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
|
const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
|
||||||
return match && match[1] || '';
|
return match && match[1] || '';
|
||||||
};
|
}
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calculate data maxRate
|
||||||
|
* @param {Number} [samplesCount= 10]
|
||||||
|
* @param {Number} [min= 1000]
|
||||||
|
* @returns {Function}
|
||||||
|
*/
|
||||||
|
function speedometer(samplesCount, min) {
|
||||||
|
samplesCount = samplesCount || 10;
|
||||||
|
const bytes = new Array(samplesCount);
|
||||||
|
const timestamps = new Array(samplesCount);
|
||||||
|
let head = 0;
|
||||||
|
let tail = 0;
|
||||||
|
let firstSampleTS;
|
||||||
|
|
||||||
|
min = min !== undefined ? min : 1000;
|
||||||
|
|
||||||
|
return function push(chunkLength) {
|
||||||
|
const now = Date.now();
|
||||||
|
|
||||||
|
const startedAt = timestamps[tail];
|
||||||
|
|
||||||
|
if (!firstSampleTS) {
|
||||||
|
firstSampleTS = now;
|
||||||
|
}
|
||||||
|
|
||||||
|
bytes[head] = chunkLength;
|
||||||
|
timestamps[head] = now;
|
||||||
|
|
||||||
|
let i = tail;
|
||||||
|
let bytesCount = 0;
|
||||||
|
|
||||||
|
while (i !== head) {
|
||||||
|
bytesCount += bytes[i++];
|
||||||
|
i = i % samplesCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
head = (head + 1) % samplesCount;
|
||||||
|
|
||||||
|
if (head === tail) {
|
||||||
|
tail = (tail + 1) % samplesCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (now - firstSampleTS < min) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const passed = startedAt && now - startedAt;
|
||||||
|
|
||||||
|
return passed ? Math.round(bytesCount * 1000 / passed) : undefined;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export default speedometer;
|
||||||
@@ -21,8 +21,8 @@
|
|||||||
*
|
*
|
||||||
* @returns {Function}
|
* @returns {Function}
|
||||||
*/
|
*/
|
||||||
module.exports = function spread(callback) {
|
export default function spread(callback) {
|
||||||
return function wrap(arr) {
|
return function wrap(arr) {
|
||||||
return callback.apply(null, arr);
|
return callback.apply(null, arr);
|
||||||
};
|
};
|
||||||
};
|
}
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Throttle decorator
|
||||||
|
* @param {Function} fn
|
||||||
|
* @param {Number} freq
|
||||||
|
* @return {Function}
|
||||||
|
*/
|
||||||
|
function throttle(fn, freq) {
|
||||||
|
let timestamp = 0;
|
||||||
|
const threshold = 1000 / freq;
|
||||||
|
let timer = null;
|
||||||
|
return function throttled(force, args) {
|
||||||
|
const now = Date.now();
|
||||||
|
if (force || now - timestamp > threshold) {
|
||||||
|
if (timer) {
|
||||||
|
clearTimeout(timer);
|
||||||
|
timer = null;
|
||||||
|
}
|
||||||
|
timestamp = now;
|
||||||
|
return fn.apply(null, args);
|
||||||
|
}
|
||||||
|
if (!timer) {
|
||||||
|
timer = setTimeout(() => {
|
||||||
|
timer = null;
|
||||||
|
timestamp = Date.now();
|
||||||
|
return fn.apply(null, args);
|
||||||
|
}, threshold - (now - timestamp));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export default throttle;
|
||||||
+18
-18
@@ -1,8 +1,8 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var utils = require('../utils');
|
import utils from '../utils.js';
|
||||||
var AxiosError = require('../core/AxiosError');
|
import AxiosError from '../core/AxiosError.js';
|
||||||
var envFormData = require('../env/classes/FormData');
|
import envFormData from '../env/classes/FormData.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Determines if the given thing is a array or js object.
|
* Determines if the given thing is a array or js object.
|
||||||
@@ -55,7 +55,7 @@ function isFlatArray(arr) {
|
|||||||
return utils.isArray(arr) && !arr.some(isVisitable);
|
return utils.isArray(arr) && !arr.some(isVisitable);
|
||||||
}
|
}
|
||||||
|
|
||||||
var predicates = utils.toFlatObject(utils, {}, null, function filter(prop) {
|
const predicates = utils.toFlatObject(utils, {}, null, function filter(prop) {
|
||||||
return /^is[A-Z]/.test(prop);
|
return /^is[A-Z]/.test(prop);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -111,13 +111,13 @@ function toFormData(obj, formData, options) {
|
|||||||
return !utils.isUndefined(source[option]);
|
return !utils.isUndefined(source[option]);
|
||||||
});
|
});
|
||||||
|
|
||||||
var metaTokens = options.metaTokens;
|
const metaTokens = options.metaTokens;
|
||||||
// eslint-disable-next-line no-use-before-define
|
// eslint-disable-next-line no-use-before-define
|
||||||
var visitor = options.visitor || defaultVisitor;
|
const visitor = options.visitor || defaultVisitor;
|
||||||
var dots = options.dots;
|
const dots = options.dots;
|
||||||
var indexes = options.indexes;
|
const indexes = options.indexes;
|
||||||
var _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;
|
const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;
|
||||||
var useBlob = _Blob && isSpecCompliant(formData);
|
const useBlob = _Blob && isSpecCompliant(formData);
|
||||||
|
|
||||||
if (!utils.isFunction(visitor)) {
|
if (!utils.isFunction(visitor)) {
|
||||||
throw new TypeError('visitor must be a function');
|
throw new TypeError('visitor must be a function');
|
||||||
@@ -152,7 +152,7 @@ function toFormData(obj, formData, options) {
|
|||||||
* @returns {boolean} return true to visit the each prop of the value recursively
|
* @returns {boolean} return true to visit the each prop of the value recursively
|
||||||
*/
|
*/
|
||||||
function defaultVisitor(value, key, path) {
|
function defaultVisitor(value, key, path) {
|
||||||
var arr = value;
|
let arr = value;
|
||||||
|
|
||||||
if (value && !path && typeof value === 'object') {
|
if (value && !path && typeof value === 'object') {
|
||||||
if (utils.endsWith(key, '{}')) {
|
if (utils.endsWith(key, '{}')) {
|
||||||
@@ -187,12 +187,12 @@ function toFormData(obj, formData, options) {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
var stack = [];
|
const stack = [];
|
||||||
|
|
||||||
var exposedHelpers = Object.assign(predicates, {
|
const exposedHelpers = Object.assign(predicates, {
|
||||||
defaultVisitor: defaultVisitor,
|
defaultVisitor,
|
||||||
convertValue: convertValue,
|
convertValue,
|
||||||
isVisitable: isVisitable
|
isVisitable
|
||||||
});
|
});
|
||||||
|
|
||||||
function build(value, path) {
|
function build(value, path) {
|
||||||
@@ -205,7 +205,7 @@ function toFormData(obj, formData, options) {
|
|||||||
stack.push(value);
|
stack.push(value);
|
||||||
|
|
||||||
utils.forEach(value, function each(el, key) {
|
utils.forEach(value, function each(el, key) {
|
||||||
var result = !utils.isUndefined(el) && visitor.call(
|
const result = !utils.isUndefined(el) && visitor.call(
|
||||||
formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers
|
formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -226,4 +226,4 @@ function toFormData(obj, formData, options) {
|
|||||||
return formData;
|
return formData;
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = toFormData;
|
export default toFormData;
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var utils = require('../utils');
|
import utils from '../utils.js';
|
||||||
var toFormData = require('./toFormData');
|
import toFormData from './toFormData.js';
|
||||||
var platform = require('../platform/');
|
import platform from '../platform/index.js';
|
||||||
|
|
||||||
module.exports = function toURLEncodedForm(data, options) {
|
export default function toURLEncodedForm(data, options) {
|
||||||
return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({
|
return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({
|
||||||
visitor: function(value, key, path, helpers) {
|
visitor: function(value, key, path, helpers) {
|
||||||
if (platform.isNode && utils.isBuffer(value)) {
|
if (platform.isNode && utils.isBuffer(value)) {
|
||||||
@@ -15,4 +15,4 @@ module.exports = function toURLEncodedForm(data, options) {
|
|||||||
return helpers.defaultVisitor.apply(this, arguments);
|
return helpers.defaultVisitor.apply(this, arguments);
|
||||||
}
|
}
|
||||||
}, options));
|
}, options));
|
||||||
};
|
}
|
||||||
|
|||||||
+15
-15
@@ -1,18 +1,18 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var VERSION = require('../env/data').version;
|
import {VERSION} from '../env/data.js';
|
||||||
var AxiosError = require('../core/AxiosError');
|
import AxiosError from '../core/AxiosError.js';
|
||||||
|
|
||||||
var validators = {};
|
const validators = {};
|
||||||
|
|
||||||
// eslint-disable-next-line func-names
|
// eslint-disable-next-line func-names
|
||||||
['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) {
|
['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {
|
||||||
validators[type] = function validator(thing) {
|
validators[type] = function validator(thing) {
|
||||||
return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
|
return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
var deprecatedWarnings = {};
|
const deprecatedWarnings = {};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Transitional option validator
|
* Transitional option validator
|
||||||
@@ -29,7 +29,7 @@ validators.transitional = function transitional(validator, version, message) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// eslint-disable-next-line func-names
|
// eslint-disable-next-line func-names
|
||||||
return function(value, opt, opts) {
|
return (value, opt, opts) => {
|
||||||
if (validator === false) {
|
if (validator === false) {
|
||||||
throw new AxiosError(
|
throw new AxiosError(
|
||||||
formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
|
formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
|
||||||
@@ -66,14 +66,14 @@ function assertOptions(options, schema, allowUnknown) {
|
|||||||
if (typeof options !== 'object') {
|
if (typeof options !== 'object') {
|
||||||
throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);
|
throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);
|
||||||
}
|
}
|
||||||
var keys = Object.keys(options);
|
const keys = Object.keys(options);
|
||||||
var i = keys.length;
|
let i = keys.length;
|
||||||
while (i-- > 0) {
|
while (i-- > 0) {
|
||||||
var opt = keys[i];
|
const opt = keys[i];
|
||||||
var validator = schema[opt];
|
const validator = schema[opt];
|
||||||
if (validator) {
|
if (validator) {
|
||||||
var value = options[opt];
|
const value = options[opt];
|
||||||
var result = value === undefined || validator(value, opt, options);
|
const result = value === undefined || validator(value, opt, options);
|
||||||
if (result !== true) {
|
if (result !== true) {
|
||||||
throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);
|
throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);
|
||||||
}
|
}
|
||||||
@@ -85,7 +85,7 @@ function assertOptions(options, schema, allowUnknown) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = {
|
export default {
|
||||||
assertOptions: assertOptions,
|
assertOptions,
|
||||||
validators: validators
|
validators
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
module.exports = FormData;
|
export default FormData;
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var AxiosURLSearchParams = require('../../../helpers/AxiosURLSearchParams');
|
import AxiosURLSearchParams from '../../../helpers/AxiosURLSearchParams.js';
|
||||||
|
export default typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;
|
||||||
module.exports = typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;
|
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
'use strict';
|
import URLSearchParams from './classes/URLSearchParams.js'
|
||||||
|
import FormData from './classes/FormData.js'
|
||||||
|
|
||||||
module.exports = {
|
export default {
|
||||||
isBrowser: true,
|
isBrowser: true,
|
||||||
classes: {
|
classes: {
|
||||||
URLSearchParams: require('./classes/URLSearchParams'),
|
URLSearchParams,
|
||||||
FormData: require('./classes/FormData'),
|
FormData,
|
||||||
Blob: Blob
|
Blob
|
||||||
},
|
},
|
||||||
protocols: ['http', 'https', 'file', 'blob', 'url']
|
protocols: ['http', 'https', 'file', 'blob', 'url']
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
'use strict';
|
import platform from './node/index.js';
|
||||||
|
|
||||||
module.exports = require('./node/');
|
export {platform as default}
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
'use strict';
|
import FormData from 'form-data';
|
||||||
|
|
||||||
module.exports = require('form-data');
|
export default FormData;
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var url = require('url');
|
import url from 'url';
|
||||||
|
export default url.URLSearchParams;
|
||||||
module.exports = url.URLSearchParams;
|
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
'use strict';
|
import URLSearchParams from './classes/URLSearchParams.js'
|
||||||
|
import FormData from './classes/FormData.js'
|
||||||
|
|
||||||
module.exports = {
|
export default {
|
||||||
isNode: true,
|
isNode: true,
|
||||||
classes: {
|
classes: {
|
||||||
URLSearchParams: require('./classes/URLSearchParams'),
|
URLSearchParams,
|
||||||
FormData: require('./classes/FormData'),
|
FormData,
|
||||||
Blob: typeof Blob !== 'undefined' && Blob || null
|
Blob: typeof Blob !== 'undefined' && Blob || null
|
||||||
},
|
},
|
||||||
protocols: [ 'http', 'https', 'file', 'data' ]
|
protocols: [ 'http', 'https', 'file', 'data' ]
|
||||||
|
|||||||
+220
-116
@@ -1,16 +1,16 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var bind = require('./helpers/bind');
|
import bind from './helpers/bind.js';
|
||||||
|
|
||||||
// utils is a library of generic helper functions non-specific to axios
|
// utils is a library of generic helper functions non-specific to axios
|
||||||
|
|
||||||
var toString = Object.prototype.toString;
|
const toString = Object.prototype.toString;
|
||||||
|
|
||||||
// eslint-disable-next-line func-names
|
// eslint-disable-next-line func-names
|
||||||
var kindOf = (function(cache) {
|
const kindOf = (cache => {
|
||||||
// eslint-disable-next-line func-names
|
// eslint-disable-next-line func-names
|
||||||
return function(thing) {
|
return thing => {
|
||||||
var str = toString.call(thing);
|
const str = toString.call(thing);
|
||||||
return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
|
return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
|
||||||
};
|
};
|
||||||
})(Object.create(null));
|
})(Object.create(null));
|
||||||
@@ -22,6 +22,12 @@ function kindOfTest(type) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function typeOfTest(type) {
|
||||||
|
return thing => {
|
||||||
|
return typeof thing === type;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Determine if a value is an Array
|
* Determine if a value is an Array
|
||||||
*
|
*
|
||||||
@@ -36,18 +42,16 @@ function isArray(val) {
|
|||||||
/**
|
/**
|
||||||
* Determine if a value is undefined
|
* Determine if a value is undefined
|
||||||
*
|
*
|
||||||
* @param {Object} val The value to test
|
* @param {*} val The value to test
|
||||||
*
|
*
|
||||||
* @returns {boolean} True if the value is undefined, otherwise false
|
* @returns {boolean} True if the value is undefined, otherwise false
|
||||||
*/
|
*/
|
||||||
function isUndefined(val) {
|
const isUndefined = typeOfTest('undefined');
|
||||||
return typeof val === 'undefined';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Determine if a value is a Buffer
|
* Determine if a value is a Buffer
|
||||||
*
|
*
|
||||||
* @param {Object} val The value to test
|
* @param {*} val The value to test
|
||||||
*
|
*
|
||||||
* @returns {boolean} True if value is a Buffer, otherwise false
|
* @returns {boolean} True if value is a Buffer, otherwise false
|
||||||
*/
|
*/
|
||||||
@@ -59,22 +63,22 @@ function isBuffer(val) {
|
|||||||
/**
|
/**
|
||||||
* Determine if a value is an ArrayBuffer
|
* Determine if a value is an ArrayBuffer
|
||||||
*
|
*
|
||||||
* @param {Object} val The value to test
|
* @param {*} val The value to test
|
||||||
*
|
*
|
||||||
* @returns {boolean} True if value is an ArrayBuffer, otherwise false
|
* @returns {boolean} True if value is an ArrayBuffer, otherwise false
|
||||||
*/
|
*/
|
||||||
var isArrayBuffer = kindOfTest('ArrayBuffer');
|
const isArrayBuffer = kindOfTest('ArrayBuffer');
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Determine if a value is a view on an ArrayBuffer
|
* Determine if a value is a view on an ArrayBuffer
|
||||||
*
|
*
|
||||||
* @param {Object} val The value to test
|
* @param {*} val The value to test
|
||||||
*
|
*
|
||||||
* @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
|
* @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
|
||||||
*/
|
*/
|
||||||
function isArrayBufferView(val) {
|
function isArrayBufferView(val) {
|
||||||
var result;
|
let result;
|
||||||
if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
|
if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
|
||||||
result = ArrayBuffer.isView(val);
|
result = ArrayBuffer.isView(val);
|
||||||
} else {
|
} else {
|
||||||
@@ -86,40 +90,54 @@ function isArrayBufferView(val) {
|
|||||||
/**
|
/**
|
||||||
* Determine if a value is a String
|
* Determine if a value is a String
|
||||||
*
|
*
|
||||||
* @param {Object} val The value to test
|
* @param {*} val The value to test
|
||||||
*
|
*
|
||||||
* @returns {boolean} True if value is a String, otherwise false
|
* @returns {boolean} True if value is a String, otherwise false
|
||||||
*/
|
*/
|
||||||
function isString(val) {
|
const isString = typeOfTest('string');
|
||||||
return typeof val === 'string';
|
|
||||||
}
|
/**
|
||||||
|
* Determine if a value is a Function
|
||||||
|
*
|
||||||
|
* @param {*} val The value to test
|
||||||
|
* @returns {boolean} True if value is a Function, otherwise false
|
||||||
|
*/
|
||||||
|
const isFunction = typeOfTest('function');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Determine if a value is a Number
|
* Determine if a value is a Number
|
||||||
*
|
*
|
||||||
* @param {Object} val The value to test
|
* @param {*} val The value to test
|
||||||
*
|
*
|
||||||
* @returns {boolean} True if value is a Number, otherwise false
|
* @returns {boolean} True if value is a Number, otherwise false
|
||||||
*/
|
*/
|
||||||
function isNumber(val) {
|
const isNumber = typeOfTest('number');
|
||||||
return typeof val === 'number';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Determine if a value is an Object
|
* Determine if a value is an Object
|
||||||
*
|
*
|
||||||
* @param {Object} val The value to test
|
* @param {*} thing The value to test
|
||||||
*
|
*
|
||||||
* @returns {boolean} True if value is an Object, otherwise false
|
* @returns {boolean} True if value is an Object, otherwise false
|
||||||
*/
|
*/
|
||||||
function isObject(val) {
|
function isObject(thing) {
|
||||||
return val !== null && typeof val === 'object';
|
return thing !== null && typeof thing === 'object';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determine if a value is a Boolean
|
||||||
|
*
|
||||||
|
* @param {*} thing The value to test
|
||||||
|
* @returns {boolean} True if value is a Boolean, otherwise false
|
||||||
|
*/
|
||||||
|
const isBoolean = thing => {
|
||||||
|
return thing === true || thing === false;
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Determine if a value is a plain Object
|
* Determine if a value is a plain Object
|
||||||
*
|
*
|
||||||
* @param {Object} val The value to test
|
* @param {*} val The value to test
|
||||||
*
|
*
|
||||||
* @returns {boolean} True if value is a plain Object, otherwise false
|
* @returns {boolean} True if value is a plain Object, otherwise false
|
||||||
*/
|
*/
|
||||||
@@ -128,61 +146,50 @@ function isPlainObject(val) {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
var prototype = Object.getPrototypeOf(val);
|
const prototype = Object.getPrototypeOf(val);
|
||||||
return prototype === null || prototype === Object.prototype;
|
return prototype === null || prototype === Object.prototype;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Determine if a value is a Date
|
* Determine if a value is a Date
|
||||||
*
|
*
|
||||||
* @param {Object} val The value to test
|
* @param {*} val The value to test
|
||||||
*
|
*
|
||||||
* @returns {boolean} True if value is a Date, otherwise false
|
* @returns {boolean} True if value is a Date, otherwise false
|
||||||
*/
|
*/
|
||||||
var isDate = kindOfTest('Date');
|
const isDate = kindOfTest('Date');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Determine if a value is a File
|
* Determine if a value is a File
|
||||||
*
|
*
|
||||||
* @param {Object} val The value to test
|
* @param {*} val The value to test
|
||||||
*
|
*
|
||||||
* @returns {boolean} True if value is a File, otherwise false
|
* @returns {boolean} True if value is a File, otherwise false
|
||||||
*/
|
*/
|
||||||
var isFile = kindOfTest('File');
|
const isFile = kindOfTest('File');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Determine if a value is a Blob
|
* Determine if a value is a Blob
|
||||||
*
|
*
|
||||||
* @param {Object} val The value to test
|
* @param {*} val The value to test
|
||||||
*
|
*
|
||||||
* @returns {boolean} True if value is a Blob, otherwise false
|
* @returns {boolean} True if value is a Blob, otherwise false
|
||||||
*/
|
*/
|
||||||
var isBlob = kindOfTest('Blob');
|
const isBlob = kindOfTest('Blob');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Determine if a value is a FileList
|
* Determine if a value is a FileList
|
||||||
*
|
*
|
||||||
* @param {Object} val The value to test
|
* @param {*} val The value to test
|
||||||
*
|
*
|
||||||
* @returns {boolean} True if value is a File, otherwise false
|
* @returns {boolean} True if value is a File, otherwise false
|
||||||
*/
|
*/
|
||||||
var isFileList = kindOfTest('FileList');
|
const isFileList = kindOfTest('FileList');
|
||||||
|
|
||||||
/**
|
|
||||||
* Determine if a value is a Function
|
|
||||||
*
|
|
||||||
* @param {Object} val The value to test
|
|
||||||
*
|
|
||||||
* @returns {boolean} True if value is a Function, otherwise false
|
|
||||||
*/
|
|
||||||
function isFunction(val) {
|
|
||||||
return toString.call(val) === '[object Function]';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Determine if a value is a Stream
|
* Determine if a value is a Stream
|
||||||
*
|
*
|
||||||
* @param {Object} val The value to test
|
* @param {*} val The value to test
|
||||||
*
|
*
|
||||||
* @returns {boolean} True if value is a Stream, otherwise false
|
* @returns {boolean} True if value is a Stream, otherwise false
|
||||||
*/
|
*/
|
||||||
@@ -193,12 +200,12 @@ function isStream(val) {
|
|||||||
/**
|
/**
|
||||||
* Determine if a value is a FormData
|
* Determine if a value is a FormData
|
||||||
*
|
*
|
||||||
* @param {Object} thing The value to test
|
* @param {*} thing The value to test
|
||||||
*
|
*
|
||||||
* @returns {boolean} True if value is an FormData, otherwise false
|
* @returns {boolean} True if value is an FormData, otherwise false
|
||||||
*/
|
*/
|
||||||
function isFormData(thing) {
|
function isFormData(thing) {
|
||||||
var pattern = '[object FormData]';
|
const pattern = '[object FormData]';
|
||||||
return thing && (
|
return thing && (
|
||||||
(typeof FormData === 'function' && thing instanceof FormData) ||
|
(typeof FormData === 'function' && thing instanceof FormData) ||
|
||||||
toString.call(thing) === pattern ||
|
toString.call(thing) === pattern ||
|
||||||
@@ -209,11 +216,11 @@ function isFormData(thing) {
|
|||||||
/**
|
/**
|
||||||
* Determine if a value is a URLSearchParams object
|
* Determine if a value is a URLSearchParams object
|
||||||
*
|
*
|
||||||
* @param {Object} val The value to test
|
* @param {*} val The value to test
|
||||||
*
|
*
|
||||||
* @returns {boolean} True if value is a URLSearchParams object, otherwise false
|
* @returns {boolean} True if value is a URLSearchParams object, otherwise false
|
||||||
*/
|
*/
|
||||||
var isURLSearchParams = kindOfTest('URLSearchParams');
|
const isURLSearchParams = kindOfTest('URLSearchParams');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Trim excess whitespace off the beginning and end of a string
|
* Trim excess whitespace off the beginning and end of a string
|
||||||
@@ -244,7 +251,7 @@ function trim(str) {
|
|||||||
* @returns {boolean}
|
* @returns {boolean}
|
||||||
*/
|
*/
|
||||||
function isStandardBrowserEnv() {
|
function isStandardBrowserEnv() {
|
||||||
var product;
|
let product;
|
||||||
if (typeof navigator !== 'undefined' && (
|
if (typeof navigator !== 'undefined' && (
|
||||||
(product = navigator.product) === 'ReactNative' ||
|
(product = navigator.product) === 'ReactNative' ||
|
||||||
product === 'NativeScript' ||
|
product === 'NativeScript' ||
|
||||||
@@ -268,14 +275,18 @@ function isStandardBrowserEnv() {
|
|||||||
* @param {Object|Array} obj The object to iterate
|
* @param {Object|Array} obj The object to iterate
|
||||||
* @param {Function} fn The callback to invoke for each item
|
* @param {Function} fn The callback to invoke for each item
|
||||||
*
|
*
|
||||||
|
* @param {Boolean} [allOwnKeys = false]
|
||||||
* @returns {void}
|
* @returns {void}
|
||||||
*/
|
*/
|
||||||
function forEach(obj, fn) {
|
function forEach(obj, fn, {allOwnKeys = false} = {}) {
|
||||||
// Don't bother if no value provided
|
// Don't bother if no value provided
|
||||||
if (obj === null || typeof obj === 'undefined') {
|
if (obj === null || typeof obj === 'undefined') {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let i;
|
||||||
|
let l;
|
||||||
|
|
||||||
// Force an array if not already something iterable
|
// Force an array if not already something iterable
|
||||||
if (typeof obj !== 'object') {
|
if (typeof obj !== 'object') {
|
||||||
/*eslint no-param-reassign:0*/
|
/*eslint no-param-reassign:0*/
|
||||||
@@ -284,15 +295,18 @@ function forEach(obj, fn) {
|
|||||||
|
|
||||||
if (isArray(obj)) {
|
if (isArray(obj)) {
|
||||||
// Iterate over array values
|
// Iterate over array values
|
||||||
for (var i = 0, l = obj.length; i < l; i++) {
|
for (i = 0, l = obj.length; i < l; i++) {
|
||||||
fn.call(null, obj[i], i, obj);
|
fn.call(null, obj[i], i, obj);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Iterate over object keys
|
// Iterate over object keys
|
||||||
for (var key in obj) {
|
const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
|
||||||
if (Object.prototype.hasOwnProperty.call(obj, key)) {
|
const len = keys.length;
|
||||||
fn.call(null, obj[key], key, obj);
|
let key;
|
||||||
}
|
|
||||||
|
for (i = 0; i < len; i++) {
|
||||||
|
key = keys[i];
|
||||||
|
fn.call(null, obj[key], key, obj);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -316,7 +330,7 @@ function forEach(obj, fn) {
|
|||||||
* @returns {Object} Result of all merge properties
|
* @returns {Object} Result of all merge properties
|
||||||
*/
|
*/
|
||||||
function merge(/* obj1, obj2, obj3, ... */) {
|
function merge(/* obj1, obj2, obj3, ... */) {
|
||||||
var result = {};
|
const result = {};
|
||||||
function assignValue(val, key) {
|
function assignValue(val, key) {
|
||||||
if (isPlainObject(result[key]) && isPlainObject(val)) {
|
if (isPlainObject(result[key]) && isPlainObject(val)) {
|
||||||
result[key] = merge(result[key], val);
|
result[key] = merge(result[key], val);
|
||||||
@@ -329,8 +343,8 @@ function merge(/* obj1, obj2, obj3, ... */) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for (var i = 0, l = arguments.length; i < l; i++) {
|
for (let i = 0, l = arguments.length; i < l; i++) {
|
||||||
forEach(arguments[i], assignValue);
|
arguments[i] && forEach(arguments[i], assignValue);
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
@@ -342,16 +356,17 @@ function merge(/* obj1, obj2, obj3, ... */) {
|
|||||||
* @param {Object} b The object to copy properties from
|
* @param {Object} b The object to copy properties from
|
||||||
* @param {Object} thisArg The object to bind function to
|
* @param {Object} thisArg The object to bind function to
|
||||||
*
|
*
|
||||||
|
* @param {Boolean} [allOwnKeys]
|
||||||
* @returns {Object} The resulting value of object a
|
* @returns {Object} The resulting value of object a
|
||||||
*/
|
*/
|
||||||
function extend(a, b, thisArg) {
|
function extend(a, b, thisArg, {allOwnKeys}= {}) {
|
||||||
forEach(b, function assignValue(val, key) {
|
forEach(b, function assignValue(val, key) {
|
||||||
if (thisArg && typeof val === 'function') {
|
if (thisArg && typeof val === 'function') {
|
||||||
a[key] = bind(val, thisArg);
|
a[key] = bind(val, thisArg);
|
||||||
} else {
|
} else {
|
||||||
a[key] = val;
|
a[key] = val;
|
||||||
}
|
}
|
||||||
});
|
}, {allOwnKeys});
|
||||||
return a;
|
return a;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -381,6 +396,9 @@ function stripBOM(content) {
|
|||||||
function inherits(constructor, superConstructor, props, descriptors) {
|
function inherits(constructor, superConstructor, props, descriptors) {
|
||||||
constructor.prototype = Object.create(superConstructor.prototype, descriptors);
|
constructor.prototype = Object.create(superConstructor.prototype, descriptors);
|
||||||
constructor.prototype.constructor = constructor;
|
constructor.prototype.constructor = constructor;
|
||||||
|
Object.defineProperty(constructor, 'super', {
|
||||||
|
value: superConstructor.prototype
|
||||||
|
});
|
||||||
props && Object.assign(constructor.prototype, props);
|
props && Object.assign(constructor.prototype, props);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -394,10 +412,10 @@ function inherits(constructor, superConstructor, props, descriptors) {
|
|||||||
* @returns {Object}
|
* @returns {Object}
|
||||||
*/
|
*/
|
||||||
function toFlatObject(sourceObj, destObj, filter, propFilter) {
|
function toFlatObject(sourceObj, destObj, filter, propFilter) {
|
||||||
var props;
|
let props;
|
||||||
var i;
|
let i;
|
||||||
var prop;
|
let prop;
|
||||||
var merged = {};
|
const merged = {};
|
||||||
|
|
||||||
destObj = destObj || {};
|
destObj = destObj || {};
|
||||||
// eslint-disable-next-line no-eq-null,eqeqeq
|
// eslint-disable-next-line no-eq-null,eqeqeq
|
||||||
@@ -434,7 +452,7 @@ function endsWith(str, searchString, position) {
|
|||||||
position = str.length;
|
position = str.length;
|
||||||
}
|
}
|
||||||
position -= searchString.length;
|
position -= searchString.length;
|
||||||
var lastIndex = str.indexOf(searchString, position);
|
const lastIndex = str.indexOf(searchString, position);
|
||||||
return lastIndex !== -1 && lastIndex === position;
|
return lastIndex !== -1 && lastIndex === position;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -449,9 +467,9 @@ function endsWith(str, searchString, position) {
|
|||||||
function toArray(thing) {
|
function toArray(thing) {
|
||||||
if (!thing) return null;
|
if (!thing) return null;
|
||||||
if (isArray(thing)) return thing;
|
if (isArray(thing)) return thing;
|
||||||
var i = thing.length;
|
let i = thing.length;
|
||||||
if (!isNumber(i)) return null;
|
if (!isNumber(i)) return null;
|
||||||
var arr = new Array(i);
|
const arr = new Array(i);
|
||||||
while (i-- > 0) {
|
while (i-- > 0) {
|
||||||
arr[i] = thing[i];
|
arr[i] = thing[i];
|
||||||
}
|
}
|
||||||
@@ -467,9 +485,9 @@ function toArray(thing) {
|
|||||||
* @returns {Array}
|
* @returns {Array}
|
||||||
*/
|
*/
|
||||||
// eslint-disable-next-line func-names
|
// eslint-disable-next-line func-names
|
||||||
var isTypedArray = (function(TypedArray) {
|
const isTypedArray = (TypedArray => {
|
||||||
// eslint-disable-next-line func-names
|
// eslint-disable-next-line func-names
|
||||||
return function(thing) {
|
return thing => {
|
||||||
return TypedArray && thing instanceof TypedArray;
|
return TypedArray && thing instanceof TypedArray;
|
||||||
};
|
};
|
||||||
})(typeof Uint8Array !== 'undefined' && Object.getPrototypeOf(Uint8Array));
|
})(typeof Uint8Array !== 'undefined' && Object.getPrototypeOf(Uint8Array));
|
||||||
@@ -483,14 +501,14 @@ var isTypedArray = (function(TypedArray) {
|
|||||||
* @returns {void}
|
* @returns {void}
|
||||||
*/
|
*/
|
||||||
function forEachEntry(obj, fn) {
|
function forEachEntry(obj, fn) {
|
||||||
var generator = obj && obj[Symbol.iterator];
|
const generator = obj && obj[Symbol.iterator];
|
||||||
|
|
||||||
var iterator = generator.call(obj);
|
const iterator = generator.call(obj);
|
||||||
|
|
||||||
var result;
|
let result;
|
||||||
|
|
||||||
while ((result = iterator.next()) && !result.done) {
|
while ((result = iterator.next()) && !result.done) {
|
||||||
var pair = result.value;
|
const pair = result.value;
|
||||||
fn.call(obj, pair[0], pair[1]);
|
fn.call(obj, pair[0], pair[1]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -504,8 +522,8 @@ function forEachEntry(obj, fn) {
|
|||||||
* @returns {Array<boolean>}
|
* @returns {Array<boolean>}
|
||||||
*/
|
*/
|
||||||
function matchAll(regExp, str) {
|
function matchAll(regExp, str) {
|
||||||
var matches;
|
let matches;
|
||||||
var arr = [];
|
const arr = [];
|
||||||
|
|
||||||
while ((matches = regExp.exec(str)) !== null) {
|
while ((matches = regExp.exec(str)) !== null) {
|
||||||
arr.push(matches);
|
arr.push(matches);
|
||||||
@@ -515,48 +533,134 @@ function matchAll(regExp, str) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */
|
/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */
|
||||||
var isHTMLForm = kindOfTest('HTMLFormElement');
|
const isHTMLForm = kindOfTest('HTMLFormElement');
|
||||||
|
|
||||||
|
const toCamelCase = str => {
|
||||||
|
return str.toLowerCase().replace(/[_-\s]([a-z\d])(\w*)/g,
|
||||||
|
function replacer(m, p1, p2) {
|
||||||
|
return p1.toUpperCase() + p2;
|
||||||
|
}
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
/* Creating a function that will check if an object has a property. */
|
/* Creating a function that will check if an object has a property. */
|
||||||
var hasOwnProperty = (function resolver(_hasOwnProperty) {
|
const hasOwnProperty = (function resolver(_hasOwnProperty) {
|
||||||
return function(obj, prop) {
|
return (obj, prop) => {
|
||||||
return _hasOwnProperty.call(obj, prop);
|
return _hasOwnProperty.call(obj, prop);
|
||||||
};
|
};
|
||||||
})(Object.prototype.hasOwnProperty);
|
})(Object.prototype.hasOwnProperty);
|
||||||
|
|
||||||
module.exports = {
|
/**
|
||||||
isArray: isArray,
|
* Determine if a value is a RegExp object
|
||||||
isArrayBuffer: isArrayBuffer,
|
*
|
||||||
isBuffer: isBuffer,
|
* @param {*} val The value to test
|
||||||
isFormData: isFormData,
|
*
|
||||||
isArrayBufferView: isArrayBufferView,
|
* @returns {boolean} True if value is a RegExp object, otherwise false
|
||||||
isString: isString,
|
*/
|
||||||
isNumber: isNumber,
|
const isRegExp = kindOfTest('RegExp');
|
||||||
isObject: isObject,
|
|
||||||
isPlainObject: isPlainObject,
|
function reduceDescriptors(obj, reducer) {
|
||||||
isUndefined: isUndefined,
|
const descriptors = Object.getOwnPropertyDescriptors(obj);
|
||||||
isDate: isDate,
|
const reducedDescriptors = {};
|
||||||
isFile: isFile,
|
|
||||||
isBlob: isBlob,
|
forEach(descriptors, (descriptor, name) => {
|
||||||
isFunction: isFunction,
|
if (reducer(descriptor, name, obj) !== false) {
|
||||||
isStream: isStream,
|
reducedDescriptors[name] = descriptor;
|
||||||
isURLSearchParams: isURLSearchParams,
|
}
|
||||||
isStandardBrowserEnv: isStandardBrowserEnv,
|
});
|
||||||
forEach: forEach,
|
|
||||||
merge: merge,
|
Object.defineProperties(obj, reducedDescriptors);
|
||||||
extend: extend,
|
}
|
||||||
trim: trim,
|
|
||||||
stripBOM: stripBOM,
|
/**
|
||||||
inherits: inherits,
|
* Makes all methods read-only
|
||||||
toFlatObject: toFlatObject,
|
* @param {Object} obj
|
||||||
kindOf: kindOf,
|
*/
|
||||||
kindOfTest: kindOfTest,
|
|
||||||
endsWith: endsWith,
|
function freezeMethods(obj) {
|
||||||
toArray: toArray,
|
reduceDescriptors(obj, (descriptor, name) => {
|
||||||
isTypedArray: isTypedArray,
|
const value = obj[name];
|
||||||
isFileList: isFileList,
|
|
||||||
forEachEntry: forEachEntry,
|
if (!isFunction(value)) return;
|
||||||
matchAll: matchAll,
|
|
||||||
isHTMLForm: isHTMLForm,
|
descriptor.enumerable = false;
|
||||||
hasOwnProperty: hasOwnProperty
|
|
||||||
|
if ('writable' in descriptor) {
|
||||||
|
descriptor.writable = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!descriptor.set) {
|
||||||
|
descriptor.set = () => {
|
||||||
|
throw Error('Can not read-only method \'' + name + '\'');
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function toObjectSet(arrayOrString, delimiter) {
|
||||||
|
const obj = {};
|
||||||
|
|
||||||
|
function define(arr) {
|
||||||
|
arr.forEach(value => {
|
||||||
|
obj[value] = true;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
|
||||||
|
|
||||||
|
return obj;
|
||||||
|
}
|
||||||
|
|
||||||
|
function noop() {}
|
||||||
|
|
||||||
|
function toFiniteNumber(value, defaultValue) {
|
||||||
|
value = +value;
|
||||||
|
return Number.isFinite(value) ? value : defaultValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default {
|
||||||
|
isArray,
|
||||||
|
isArrayBuffer,
|
||||||
|
isBuffer,
|
||||||
|
isFormData,
|
||||||
|
isArrayBufferView,
|
||||||
|
isString,
|
||||||
|
isNumber,
|
||||||
|
isBoolean,
|
||||||
|
isObject,
|
||||||
|
isPlainObject,
|
||||||
|
isUndefined,
|
||||||
|
isDate,
|
||||||
|
isFile,
|
||||||
|
isBlob,
|
||||||
|
isRegExp,
|
||||||
|
isFunction,
|
||||||
|
isStream,
|
||||||
|
isURLSearchParams,
|
||||||
|
isTypedArray,
|
||||||
|
isFileList,
|
||||||
|
isStandardBrowserEnv,
|
||||||
|
forEach,
|
||||||
|
merge,
|
||||||
|
extend,
|
||||||
|
trim,
|
||||||
|
stripBOM,
|
||||||
|
inherits,
|
||||||
|
toFlatObject,
|
||||||
|
kindOf,
|
||||||
|
kindOfTest,
|
||||||
|
endsWith,
|
||||||
|
toArray,
|
||||||
|
forEachEntry,
|
||||||
|
matchAll,
|
||||||
|
isHTMLForm,
|
||||||
|
hasOwnProperty,
|
||||||
|
hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection
|
||||||
|
reduceDescriptors,
|
||||||
|
freezeMethods,
|
||||||
|
toObjectSet,
|
||||||
|
toCamelCase,
|
||||||
|
noop,
|
||||||
|
toFiniteNumber
|
||||||
};
|
};
|
||||||
|
|||||||
Generated
+6948
-5354
File diff suppressed because it is too large
Load Diff
+53
-21
@@ -3,12 +3,33 @@
|
|||||||
"version": "1.0.0-alpha.1",
|
"version": "1.0.0-alpha.1",
|
||||||
"description": "Promise based HTTP client for the browser and node.js",
|
"description": "Promise based HTTP client for the browser and node.js",
|
||||||
"main": "index.js",
|
"main": "index.js",
|
||||||
|
"exports": {
|
||||||
|
".": {
|
||||||
|
"browser": {
|
||||||
|
"require": "./index.js",
|
||||||
|
"default": "./index.js"
|
||||||
|
},
|
||||||
|
"default": {
|
||||||
|
"require": "./dist/node/axios.cjs",
|
||||||
|
"default": "./index.js"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"type": "module",
|
||||||
"types": "index.d.ts",
|
"types": "index.d.ts",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "node bin/ssl_hotfix.js grunt test && node bin/ssl_hotfix.js dtslint",
|
"test": "npm run test:eslint && npm run test:mocha && npm run test:karma && npm run test:dtslint",
|
||||||
|
"test:eslint": "node bin/ssl_hotfix.js eslint lib/**/*.js",
|
||||||
|
"test:dtslint": "node bin/ssl_hotfix.js dtslint",
|
||||||
|
"test:mocha": "node bin/ssl_hotfix.js mocha test/unit/**/*.js --timeout 30000 --exit",
|
||||||
|
"test:karma": "node bin/ssl_hotfix.js cross-env LISTEN_ADDR=:: karma start karma.conf.cjs --single-run",
|
||||||
|
"test:karma:server": "node bin/ssl_hotfix.js cross-env karma start karma.conf.cjs",
|
||||||
"start": "node ./sandbox/server.js",
|
"start": "node ./sandbox/server.js",
|
||||||
"preversion": "grunt version && npm test",
|
"preversion": "gulp version && npm test",
|
||||||
"build": "cross-env NODE_ENV=production grunt build",
|
"version": "npm run build && git add dist && git add package.json",
|
||||||
|
"prepublishOnly": "npm test",
|
||||||
|
"postpublish": "git push && git push --tags ",
|
||||||
|
"build": "gulp clear && cross-env NODE_ENV=production rollup -c -m",
|
||||||
"examples": "node ./examples/server.js",
|
"examples": "node ./examples/server.js",
|
||||||
"coveralls": "cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js",
|
"coveralls": "cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js",
|
||||||
"fix": "eslint --fix lib/**/*.js"
|
"fix": "eslint --fix lib/**/*.js"
|
||||||
@@ -31,7 +52,8 @@
|
|||||||
},
|
},
|
||||||
"homepage": "https://axios-http.com",
|
"homepage": "https://axios-http.com",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@rollup/plugin-babel": "^5.3.0",
|
"@babel/preset-env": "^7.18.2",
|
||||||
|
"@rollup/plugin-babel": "^5.3.1",
|
||||||
"@rollup/plugin-commonjs": "^15.1.0",
|
"@rollup/plugin-commonjs": "^15.1.0",
|
||||||
"@rollup/plugin-json": "^4.1.0",
|
"@rollup/plugin-json": "^4.1.0",
|
||||||
"@rollup/plugin-multi-entry": "^4.0.0",
|
"@rollup/plugin-multi-entry": "^4.0.0",
|
||||||
@@ -40,20 +62,15 @@
|
|||||||
"body-parser": "^1.20.0",
|
"body-parser": "^1.20.0",
|
||||||
"coveralls": "^3.1.1",
|
"coveralls": "^3.1.1",
|
||||||
"cross-env": "^7.0.3",
|
"cross-env": "^7.0.3",
|
||||||
|
"dev-null": "^0.1.1",
|
||||||
"dtslint": "^4.2.1",
|
"dtslint": "^4.2.1",
|
||||||
"es6-promise": "^4.2.8",
|
"es6-promise": "^4.2.8",
|
||||||
|
"eslint": "^8.17.0",
|
||||||
"express": "^4.18.1",
|
"express": "^4.18.1",
|
||||||
"formidable": "^2.0.1",
|
"formidable": "^2.0.1",
|
||||||
"grunt": "^1.4.1",
|
"fs-extra": "^10.1.0",
|
||||||
"grunt-banner": "^0.6.0",
|
"get-stream": "^3.0.0",
|
||||||
"grunt-cli": "^1.4.3",
|
"gulp": "^4.0.2",
|
||||||
"grunt-contrib-clean": "^2.0.0",
|
|
||||||
"grunt-contrib-watch": "^1.1.0",
|
|
||||||
"grunt-eslint": "^24.0.0",
|
|
||||||
"grunt-karma": "^4.0.2",
|
|
||||||
"grunt-mocha-test": "^0.13.3",
|
|
||||||
"grunt-shell": "^3.0.1",
|
|
||||||
"grunt-webpack": "^5.0.0",
|
|
||||||
"istanbul-instrumenter-loader": "^3.0.1",
|
"istanbul-instrumenter-loader": "^3.0.1",
|
||||||
"jasmine-core": "^2.4.1",
|
"jasmine-core": "^2.4.1",
|
||||||
"karma": "^6.3.17",
|
"karma": "^6.3.17",
|
||||||
@@ -61,23 +78,22 @@
|
|||||||
"karma-firefox-launcher": "^2.1.2",
|
"karma-firefox-launcher": "^2.1.2",
|
||||||
"karma-jasmine": "^1.1.1",
|
"karma-jasmine": "^1.1.1",
|
||||||
"karma-jasmine-ajax": "^0.1.13",
|
"karma-jasmine-ajax": "^0.1.13",
|
||||||
|
"karma-rollup-preprocessor": "^7.0.8",
|
||||||
"karma-safari-launcher": "^1.0.0",
|
"karma-safari-launcher": "^1.0.0",
|
||||||
"karma-sauce-launcher": "^4.3.6",
|
"karma-sauce-launcher": "^4.3.6",
|
||||||
"karma-sinon": "^1.0.5",
|
"karma-sinon": "^1.0.5",
|
||||||
"karma-sourcemap-loader": "^0.3.8",
|
"karma-sourcemap-loader": "^0.3.8",
|
||||||
"karma-webpack": "^4.0.2",
|
|
||||||
"load-grunt-tasks": "^5.1.0",
|
|
||||||
"minimist": "^1.2.6",
|
"minimist": "^1.2.6",
|
||||||
"mocha": "^8.2.1",
|
"mocha": "^10.0.0",
|
||||||
"multer": "^1.4.4",
|
"multer": "^1.4.4",
|
||||||
"rollup": "^2.67.0",
|
"rollup": "^2.67.0",
|
||||||
|
"rollup-plugin-auto-external": "^2.0.0",
|
||||||
"rollup-plugin-terser": "^7.0.2",
|
"rollup-plugin-terser": "^7.0.2",
|
||||||
"sinon": "^4.5.0",
|
"sinon": "^4.5.0",
|
||||||
|
"stream-throttle": "^0.1.3",
|
||||||
"terser-webpack-plugin": "^4.2.3",
|
"terser-webpack-plugin": "^4.2.3",
|
||||||
"typescript": "^4.6.3",
|
"typescript": "^4.6.3",
|
||||||
"url-search-params": "^0.10.0",
|
"url-search-params": "^0.10.0"
|
||||||
"webpack": "^4.44.2",
|
|
||||||
"webpack-dev-server": "^3.11.0"
|
|
||||||
},
|
},
|
||||||
"browser": {
|
"browser": {
|
||||||
"./lib/adapters/http.js": "./lib/adapters/xhr.js",
|
"./lib/adapters/http.js": "./lib/adapters/xhr.js",
|
||||||
@@ -96,5 +112,21 @@
|
|||||||
"path": "./dist/axios.min.js",
|
"path": "./dist/axios.min.js",
|
||||||
"threshold": "5kB"
|
"threshold": "5kB"
|
||||||
}
|
}
|
||||||
|
],
|
||||||
|
"contributors": [
|
||||||
|
"Matt Zabriskie (https://github.com/mzabriskie)",
|
||||||
|
"Nick Uraltsev (https://github.com/nickuraltsev)",
|
||||||
|
"Jay (https://github.com/jasonsaayman)",
|
||||||
|
"Emily Morehouse (https://github.com/emilyemorehouse)",
|
||||||
|
"Dmitriy Mozgovoy (https://github.com/DigitalBrainJS)",
|
||||||
|
"Rubén Norte (https://github.com/rubennorte)",
|
||||||
|
"Justin Beckwith (https://github.com/JustinBeckwith)",
|
||||||
|
"Martti Laine (https://github.com/codeclown)",
|
||||||
|
"Xianming Zhong (https://github.com/chinesedfan)",
|
||||||
|
"Rikki Gibson (https://github.com/RikkiGibson)",
|
||||||
|
"Remco Haszing (https://github.com/remcohaszing)",
|
||||||
|
"Yasu Flores (https://github.com/yasuf)",
|
||||||
|
"Ben Carp (https://github.com/carpben)",
|
||||||
|
"Daniel Lopretto (https://github.com/timemachine3030)"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
+34
-6
@@ -2,13 +2,15 @@ import resolve from '@rollup/plugin-node-resolve';
|
|||||||
import commonjs from '@rollup/plugin-commonjs';
|
import commonjs from '@rollup/plugin-commonjs';
|
||||||
import {terser} from "rollup-plugin-terser";
|
import {terser} from "rollup-plugin-terser";
|
||||||
import json from '@rollup/plugin-json';
|
import json from '@rollup/plugin-json';
|
||||||
|
import { babel } from '@rollup/plugin-babel';
|
||||||
|
import autoExternal from 'rollup-plugin-auto-external';
|
||||||
|
|
||||||
const lib = require("./package.json");
|
const lib = require("./package.json");
|
||||||
const outputFileName = 'axios';
|
const outputFileName = 'axios';
|
||||||
const name = "axios";
|
const name = "axios";
|
||||||
const input = './lib/axios.js';
|
const input = './lib/axios.js';
|
||||||
|
|
||||||
const buildConfig = (config) => {
|
const buildConfig = ({es5, browser = true, minifiedVersion = true, ...config}) => {
|
||||||
|
|
||||||
const build = ({minified}) => ({
|
const build = ({minified}) => ({
|
||||||
input,
|
input,
|
||||||
@@ -19,25 +21,35 @@ const buildConfig = (config) => {
|
|||||||
},
|
},
|
||||||
plugins: [
|
plugins: [
|
||||||
json(),
|
json(),
|
||||||
resolve({browser: true}),
|
resolve({browser}),
|
||||||
commonjs(),
|
commonjs(),
|
||||||
minified && terser(),
|
minified && terser(),
|
||||||
|
...(es5 ? [babel({
|
||||||
|
babelHelpers: 'bundled',
|
||||||
|
presets: ['@babel/preset-env']
|
||||||
|
})] : []),
|
||||||
...(config.plugins || []),
|
...(config.plugins || []),
|
||||||
]
|
]
|
||||||
});
|
});
|
||||||
|
|
||||||
return [
|
const configs = [
|
||||||
build({minified: false}),
|
build({minified: false}),
|
||||||
build({minified: true}),
|
|
||||||
];
|
];
|
||||||
|
|
||||||
|
if (minifiedVersion) {
|
||||||
|
build({minified: true})
|
||||||
|
}
|
||||||
|
|
||||||
|
return configs;
|
||||||
};
|
};
|
||||||
|
|
||||||
export default async () => {
|
export default async () => {
|
||||||
const year = new Date().getFullYear();
|
const year = new Date().getFullYear();
|
||||||
const banner = `// ${lib.name} v${lib.version} Copyright (c) ${year} ${lib.author}`;
|
const banner = `// Axios v${lib.version} Copyright (c) ${year} ${lib.author} and contributors`;
|
||||||
|
|
||||||
return [
|
return [
|
||||||
...buildConfig({
|
...buildConfig({
|
||||||
|
es5: true,
|
||||||
output: {
|
output: {
|
||||||
file: `dist/${outputFileName}`,
|
file: `dist/${outputFileName}`,
|
||||||
name,
|
name,
|
||||||
@@ -55,6 +67,22 @@ export default async () => {
|
|||||||
exports: "named",
|
exports: "named",
|
||||||
banner
|
banner
|
||||||
}
|
}
|
||||||
})
|
}),
|
||||||
|
// Node.js commonjs build
|
||||||
|
{
|
||||||
|
input,
|
||||||
|
output: {
|
||||||
|
file: `dist/node/${name}.cjs`,
|
||||||
|
format: "cjs",
|
||||||
|
preferConst: true,
|
||||||
|
exports: "default",
|
||||||
|
banner
|
||||||
|
},
|
||||||
|
plugins: [
|
||||||
|
autoExternal(),
|
||||||
|
resolve(),
|
||||||
|
commonjs()
|
||||||
|
]
|
||||||
|
}
|
||||||
]
|
]
|
||||||
};
|
};
|
||||||
|
|||||||
+3
-3
@@ -1,7 +1,7 @@
|
|||||||
var axios = require('../index');
|
import axios from '../index';
|
||||||
|
|
||||||
var URL = 'http://127.0.0.1:3000/api';
|
const URL = 'http://127.0.0.1:3000/api';
|
||||||
var BODY = {
|
const BODY = {
|
||||||
foo: 'bar',
|
foo: 'bar',
|
||||||
baz: 1234
|
baz: 1234
|
||||||
};
|
};
|
||||||
|
|||||||
+10
-10
@@ -1,8 +1,8 @@
|
|||||||
var fs = require('fs');
|
import fs from 'fs';
|
||||||
var url = require('url');
|
import url from 'url';
|
||||||
var path = require('path');
|
import path from 'path';
|
||||||
var http = require('http');
|
import http from 'http';
|
||||||
var server;
|
let server;
|
||||||
|
|
||||||
function pipeFileToResponse(res, file, type) {
|
function pipeFileToResponse(res, file, type) {
|
||||||
if (type) {
|
if (type) {
|
||||||
@@ -17,8 +17,8 @@ function pipeFileToResponse(res, file, type) {
|
|||||||
server = http.createServer(function (req, res) {
|
server = http.createServer(function (req, res) {
|
||||||
req.setEncoding('utf8');
|
req.setEncoding('utf8');
|
||||||
|
|
||||||
var parsed = url.parse(req.url, true);
|
const parsed = url.parse(req.url, true);
|
||||||
var pathname = parsed.pathname;
|
let pathname = parsed.pathname;
|
||||||
|
|
||||||
console.log('[' + new Date() + ']', req.method, pathname);
|
console.log('[' + new Date() + ']', req.method, pathname);
|
||||||
|
|
||||||
@@ -33,9 +33,9 @@ server = http.createServer(function (req, res) {
|
|||||||
} else if (pathname === '/axios.map') {
|
} else if (pathname === '/axios.map') {
|
||||||
pipeFileToResponse(res, '../dist/axios.map', 'text/javascript');
|
pipeFileToResponse(res, '../dist/axios.map', 'text/javascript');
|
||||||
} else if (pathname === '/api') {
|
} else if (pathname === '/api') {
|
||||||
var status;
|
let status;
|
||||||
var result;
|
let result;
|
||||||
var data = '';
|
let data = '';
|
||||||
|
|
||||||
req.on('data', function (chunk) {
|
req.on('data', function (chunk) {
|
||||||
data += chunk;
|
data += chunk;
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
See your console
|
||||||
|
<script src="../../dist/axios.js"></script>
|
||||||
|
<script>
|
||||||
|
const data = new Int8Array(10 * 1024 * 1024);
|
||||||
|
|
||||||
|
data.fill(123);
|
||||||
|
|
||||||
|
axios.post('http://httpbin.org/post', data, {
|
||||||
|
onUploadProgress: console.log,
|
||||||
|
onDownloadProgress: console.log,
|
||||||
|
}).then(data=> {
|
||||||
|
console.log(`Done: `, data);
|
||||||
|
}).catch(console.warn);
|
||||||
|
|
||||||
|
</script>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
+28
-110
@@ -1,123 +1,41 @@
|
|||||||
// Polyfill ES6 Promise
|
import _axios from '../../index.js';
|
||||||
require('es6-promise').polyfill();
|
|
||||||
|
|
||||||
// Polyfill URLSearchParams
|
window.axios = _axios;
|
||||||
URLSearchParams = require('url-search-params');
|
|
||||||
|
|
||||||
// Import axios
|
|
||||||
axios = require('../../index');
|
|
||||||
|
|
||||||
// Jasmine config
|
// Jasmine config
|
||||||
jasmine.DEFAULT_TIMEOUT_INTERVAL = 20000;
|
jasmine.DEFAULT_TIMEOUT_INTERVAL = 20000;
|
||||||
jasmine.getEnv().defaultTimeoutInterval = 20000;
|
jasmine.getEnv().defaultTimeoutInterval = 20000;
|
||||||
|
|
||||||
// Get Ajax request using an increasing timeout to retry
|
// Get Ajax request using an increasing timeout to retry
|
||||||
getAjaxRequest = (function () {
|
window.getAjaxRequest = (function () {
|
||||||
var attempts = 0;
|
let attempts = 0;
|
||||||
var MAX_ATTEMPTS = 5;
|
const MAX_ATTEMPTS = 5;
|
||||||
var ATTEMPT_DELAY_FACTOR = 5;
|
const ATTEMPT_DELAY_FACTOR = 5;
|
||||||
|
|
||||||
function getAjaxRequest() {
|
function getAjaxRequest() {
|
||||||
return new Promise(function (resolve, reject) {
|
return new Promise(function (resolve, reject) {
|
||||||
attempts = 0;
|
attempts = 0;
|
||||||
attemptGettingAjaxRequest(resolve, reject);
|
attemptGettingAjaxRequest(resolve, reject);
|
||||||
});
|
});
|
||||||
}
|
|
||||||
|
|
||||||
function attemptGettingAjaxRequest(resolve, reject) {
|
|
||||||
var delay = attempts * attempts * ATTEMPT_DELAY_FACTOR;
|
|
||||||
|
|
||||||
if (attempts++ > MAX_ATTEMPTS) {
|
|
||||||
reject(new Error('No request was found'));
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
setTimeout(function () {
|
function attemptGettingAjaxRequest(resolve, reject) {
|
||||||
var request = jasmine.Ajax.requests.mostRecent();
|
const delay = attempts * attempts * ATTEMPT_DELAY_FACTOR;
|
||||||
if (request) {
|
|
||||||
resolve(request);
|
if (attempts++ > MAX_ATTEMPTS) {
|
||||||
} else {
|
reject(new Error('No request was found'));
|
||||||
attemptGettingAjaxRequest(resolve, reject);
|
return;
|
||||||
}
|
}
|
||||||
}, delay);
|
|
||||||
}
|
|
||||||
|
|
||||||
return getAjaxRequest;
|
setTimeout(function () {
|
||||||
|
const request = jasmine.Ajax.requests.mostRecent();
|
||||||
|
if (request) {
|
||||||
|
resolve(request);
|
||||||
|
} else {
|
||||||
|
attemptGettingAjaxRequest(resolve, reject);
|
||||||
|
}
|
||||||
|
}, delay);
|
||||||
|
}
|
||||||
|
|
||||||
|
return getAjaxRequest;
|
||||||
})();
|
})();
|
||||||
|
|
||||||
// Validate an invalid character error
|
|
||||||
validateInvalidCharacterError = function validateInvalidCharacterError(error) {
|
|
||||||
expect(/character/i.test(error.message)).toEqual(true);
|
|
||||||
};
|
|
||||||
|
|
||||||
// Setup basic auth tests
|
|
||||||
setupBasicAuthTest = function setupBasicAuthTest() {
|
|
||||||
beforeEach(function () {
|
|
||||||
jasmine.Ajax.install();
|
|
||||||
});
|
|
||||||
|
|
||||||
afterEach(function () {
|
|
||||||
jasmine.Ajax.uninstall();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should accept HTTP Basic auth with username/password', function (done) {
|
|
||||||
axios('/foo', {
|
|
||||||
auth: {
|
|
||||||
username: 'Aladdin',
|
|
||||||
password: 'open sesame'
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
setTimeout(function () {
|
|
||||||
var request = jasmine.Ajax.requests.mostRecent();
|
|
||||||
|
|
||||||
expect(request.requestHeaders['Authorization']).toEqual('Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==');
|
|
||||||
done();
|
|
||||||
}, 100);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should accept HTTP Basic auth credentials without the password parameter', function (done) {
|
|
||||||
axios('/foo', {
|
|
||||||
auth: {
|
|
||||||
username: 'Aladdin'
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
setTimeout(function () {
|
|
||||||
var request = jasmine.Ajax.requests.mostRecent();
|
|
||||||
|
|
||||||
expect(request.requestHeaders['Authorization']).toEqual('Basic QWxhZGRpbjo=');
|
|
||||||
done();
|
|
||||||
}, 100);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should accept HTTP Basic auth credentials with non-Latin1 characters in password', function (done) {
|
|
||||||
axios('/foo', {
|
|
||||||
auth: {
|
|
||||||
username: 'Aladdin',
|
|
||||||
password: 'open ßç£☃sesame'
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
setTimeout(function () {
|
|
||||||
var request = jasmine.Ajax.requests.mostRecent();
|
|
||||||
|
|
||||||
expect(request.requestHeaders['Authorization']).toEqual('Basic QWxhZGRpbjpvcGVuIMOfw6fCo+KYg3Nlc2FtZQ==');
|
|
||||||
done();
|
|
||||||
}, 100);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should fail to encode HTTP Basic auth credentials with non-Latin1 characters in username', function (done) {
|
|
||||||
axios('/foo', {
|
|
||||||
auth: {
|
|
||||||
username: 'Aladßç£☃din',
|
|
||||||
password: 'open sesame'
|
|
||||||
}
|
|
||||||
}).then(function(response) {
|
|
||||||
done(new Error('Should not succeed to make a HTTP Basic auth request with non-latin1 chars in credentials.'));
|
|
||||||
}).catch(function(error) {
|
|
||||||
validateInvalidCharacterError(error);
|
|
||||||
done();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
var axios = require('../../index');
|
|
||||||
|
|
||||||
describe('adapter', function () {
|
describe('adapter', function () {
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
@@ -13,7 +12,7 @@ describe('adapter', function () {
|
|||||||
axios('/foo', {
|
axios('/foo', {
|
||||||
adapter: function barAdapter(config) {
|
adapter: function barAdapter(config) {
|
||||||
return new Promise(function dispatchXhrRequest(resolve) {
|
return new Promise(function dispatchXhrRequest(resolve) {
|
||||||
var request = new XMLHttpRequest();
|
const request = new XMLHttpRequest();
|
||||||
request.open('GET', '/bar');
|
request.open('GET', '/bar');
|
||||||
|
|
||||||
request.onreadystatechange = function () {
|
request.onreadystatechange = function () {
|
||||||
@@ -26,7 +25,7 @@ describe('adapter', function () {
|
|||||||
request.send(null);
|
request.send(null);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}).catch(console.log);
|
}).catch(done);
|
||||||
|
|
||||||
getAjaxRequest().then(function(request) {
|
getAjaxRequest().then(function(request) {
|
||||||
expect(request.url).toBe('/bar');
|
expect(request.url).toBe('/bar');
|
||||||
@@ -35,11 +34,11 @@ describe('adapter', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should execute adapter code synchronously', function (done) {
|
it('should execute adapter code synchronously', function (done) {
|
||||||
var asyncFlag = false;
|
let asyncFlag = false;
|
||||||
axios('/foo', {
|
axios('/foo', {
|
||||||
adapter: function barAdapter(config) {
|
adapter: function barAdapter(config) {
|
||||||
return new Promise(function dispatchXhrRequest(resolve) {
|
return new Promise(function dispatchXhrRequest(resolve) {
|
||||||
var request = new XMLHttpRequest();
|
const request = new XMLHttpRequest();
|
||||||
request.open('GET', '/bar');
|
request.open('GET', '/bar');
|
||||||
|
|
||||||
request.onreadystatechange = function () {
|
request.onreadystatechange = function () {
|
||||||
@@ -53,7 +52,7 @@ describe('adapter', function () {
|
|||||||
request.send(null);
|
request.send(null);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}).catch(console.log);
|
}).catch(done);
|
||||||
|
|
||||||
asyncFlag = true;
|
asyncFlag = true;
|
||||||
|
|
||||||
@@ -63,7 +62,7 @@ describe('adapter', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should execute adapter code asynchronously when interceptor is present', function (done) {
|
it('should execute adapter code asynchronously when interceptor is present', function (done) {
|
||||||
var asyncFlag = false;
|
let asyncFlag = false;
|
||||||
|
|
||||||
axios.interceptors.request.use(function (config) {
|
axios.interceptors.request.use(function (config) {
|
||||||
config.headers.async = 'async it!';
|
config.headers.async = 'async it!';
|
||||||
@@ -73,7 +72,7 @@ describe('adapter', function () {
|
|||||||
axios('/foo', {
|
axios('/foo', {
|
||||||
adapter: function barAdapter(config) {
|
adapter: function barAdapter(config) {
|
||||||
return new Promise(function dispatchXhrRequest(resolve) {
|
return new Promise(function dispatchXhrRequest(resolve) {
|
||||||
var request = new XMLHttpRequest();
|
const request = new XMLHttpRequest();
|
||||||
request.open('GET', '/bar');
|
request.open('GET', '/bar');
|
||||||
|
|
||||||
request.onreadystatechange = function () {
|
request.onreadystatechange = function () {
|
||||||
@@ -87,7 +86,7 @@ describe('adapter', function () {
|
|||||||
request.send(null);
|
request.send(null);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}).catch(console.log);
|
}).catch(done);
|
||||||
|
|
||||||
asyncFlag = true;
|
asyncFlag = true;
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
|
||||||
describe('static api', function () {
|
describe('static api', function () {
|
||||||
it('should have request method helpers', function () {
|
it('should have request method helpers', function () {
|
||||||
expect(typeof axios.request).toEqual('function');
|
expect(typeof axios.request).toEqual('function');
|
||||||
@@ -11,7 +12,7 @@ describe('static api', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should have promise method helpers', function () {
|
it('should have promise method helpers', function () {
|
||||||
var promise = axios('/test');
|
const promise = axios('/test');
|
||||||
|
|
||||||
expect(typeof promise.then).toEqual('function');
|
expect(typeof promise.then).toEqual('function');
|
||||||
expect(typeof promise.catch).toEqual('function');
|
expect(typeof promise.catch).toEqual('function');
|
||||||
@@ -52,7 +53,7 @@ describe('static api', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('instance api', function () {
|
describe('instance api', function () {
|
||||||
var instance = axios.create();
|
const instance = axios.create();
|
||||||
|
|
||||||
it('should have request methods', function () {
|
it('should have request methods', function () {
|
||||||
expect(typeof instance.request).toEqual('function');
|
expect(typeof instance.request).toEqual('function');
|
||||||
|
|||||||
@@ -1,3 +1,77 @@
|
|||||||
|
import axios from "../../index";
|
||||||
|
|
||||||
|
function validateInvalidCharacterError(error) {
|
||||||
|
expect(/character/i.test(error.message)).toEqual(true);
|
||||||
|
};
|
||||||
|
|
||||||
describe('basicAuth', function () {
|
describe('basicAuth', function () {
|
||||||
setupBasicAuthTest();
|
// Validate an invalid character error
|
||||||
|
beforeEach(function () {
|
||||||
|
jasmine.Ajax.install();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(function () {
|
||||||
|
jasmine.Ajax.uninstall();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should accept HTTP Basic auth with username/password', function (done) {
|
||||||
|
axios('/foo', {
|
||||||
|
auth: {
|
||||||
|
username: 'Aladdin',
|
||||||
|
password: 'open sesame'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
setTimeout(function () {
|
||||||
|
const request = jasmine.Ajax.requests.mostRecent();
|
||||||
|
|
||||||
|
expect(request.requestHeaders['Authorization']).toEqual('Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==');
|
||||||
|
done();
|
||||||
|
}, 100);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should accept HTTP Basic auth credentials without the password parameter', function (done) {
|
||||||
|
axios('/foo', {
|
||||||
|
auth: {
|
||||||
|
username: 'Aladdin'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
setTimeout(function () {
|
||||||
|
const request = jasmine.Ajax.requests.mostRecent();
|
||||||
|
|
||||||
|
expect(request.requestHeaders['Authorization']).toEqual('Basic QWxhZGRpbjo=');
|
||||||
|
done();
|
||||||
|
}, 100);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should accept HTTP Basic auth credentials with non-Latin1 characters in password', function (done) {
|
||||||
|
axios('/foo', {
|
||||||
|
auth: {
|
||||||
|
username: 'Aladdin',
|
||||||
|
password: 'open ßç£☃sesame'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
setTimeout(function () {
|
||||||
|
const request = jasmine.Ajax.requests.mostRecent();
|
||||||
|
|
||||||
|
expect(request.requestHeaders['Authorization']).toEqual('Basic QWxhZGRpbjpvcGVuIMOfw6fCo+KYg3Nlc2FtZQ==');
|
||||||
|
done();
|
||||||
|
}, 100);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should fail to encode HTTP Basic auth credentials with non-Latin1 characters in username', function (done) {
|
||||||
|
axios('/foo', {
|
||||||
|
auth: {
|
||||||
|
username: 'Aladßç£☃din',
|
||||||
|
password: 'open sesame'
|
||||||
|
}
|
||||||
|
}).then(function (response) {
|
||||||
|
done(new Error('Should not succeed to make a HTTP Basic auth request with non-latin1 chars in credentials.'));
|
||||||
|
}).catch(function (error) {
|
||||||
|
validateInvalidCharacterError(error);
|
||||||
|
done();
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
var Cancel = axios.Cancel;
|
const Cancel = axios.Cancel;
|
||||||
var CancelToken = axios.CancelToken;
|
const CancelToken = axios.CancelToken;
|
||||||
var _AbortController = require('abortcontroller-polyfill/dist/cjs-ponyfill.js').AbortController;
|
import {AbortController as _AbortController} from 'abortcontroller-polyfill/dist/cjs-ponyfill.js';
|
||||||
|
|
||||||
var AbortController = typeof AbortController === 'function' ? AbortController : _AbortController;
|
const envAbortController = typeof AbortController === 'function' ? AbortController : _AbortController;
|
||||||
|
|
||||||
describe('cancel', function() {
|
describe('cancel', function() {
|
||||||
beforeEach(function() {
|
beforeEach(function() {
|
||||||
@@ -15,7 +15,7 @@ describe('cancel', function() {
|
|||||||
|
|
||||||
describe('when called before sending request', function() {
|
describe('when called before sending request', function() {
|
||||||
it('rejects Promise with a CanceledError object', function(done) {
|
it('rejects Promise with a CanceledError object', function(done) {
|
||||||
var source = CancelToken.source();
|
const source = CancelToken.source();
|
||||||
source.cancel('Operation has been canceled.');
|
source.cancel('Operation has been canceled.');
|
||||||
axios.get('/foo', {
|
axios.get('/foo', {
|
||||||
cancelToken: source.token
|
cancelToken: source.token
|
||||||
@@ -29,7 +29,7 @@ describe('cancel', function() {
|
|||||||
|
|
||||||
describe('when called after request has been sent', function() {
|
describe('when called after request has been sent', function() {
|
||||||
it('rejects Promise with a CanceledError object', function(done) {
|
it('rejects Promise with a CanceledError object', function(done) {
|
||||||
var source = CancelToken.source();
|
const source = CancelToken.source();
|
||||||
axios.get('/foo/bar', {
|
axios.get('/foo/bar', {
|
||||||
cancelToken: source.token
|
cancelToken: source.token
|
||||||
}).catch(function(thrown) {
|
}).catch(function(thrown) {
|
||||||
@@ -49,8 +49,8 @@ describe('cancel', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('calls abort on request object', function(done) {
|
it('calls abort on request object', function(done) {
|
||||||
var source = CancelToken.source();
|
const source = CancelToken.source();
|
||||||
var request;
|
let request;
|
||||||
axios.get('/foo/bar', {
|
axios.get('/foo/bar', {
|
||||||
cancelToken: source.token
|
cancelToken: source.token
|
||||||
}).catch(function() {
|
}).catch(function() {
|
||||||
@@ -91,7 +91,7 @@ describe('cancel', function() {
|
|||||||
// });
|
// });
|
||||||
|
|
||||||
it('it should support cancellation using AbortController signal', function(done) {
|
it('it should support cancellation using AbortController signal', function(done) {
|
||||||
var controller = new AbortController();
|
const controller = new envAbortController();
|
||||||
|
|
||||||
axios.get('/foo/bar', {
|
axios.get('/foo/bar', {
|
||||||
signal: controller.signal
|
signal: controller.signal
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
var CancelToken = require('../../../lib/cancel/CancelToken');
|
import CancelToken from '../../../lib/cancel/CancelToken';
|
||||||
var CanceledError = require('../../../lib/cancel/CanceledError');
|
import CanceledError from '../../../lib/cancel/CanceledError';
|
||||||
|
|
||||||
describe('CancelToken', function() {
|
describe('CancelToken', function() {
|
||||||
describe('constructor', function() {
|
describe('constructor', function() {
|
||||||
@@ -18,8 +18,8 @@ describe('CancelToken', function() {
|
|||||||
|
|
||||||
describe('reason', function() {
|
describe('reason', function() {
|
||||||
it('returns a CanceledError if cancellation has been requested', function() {
|
it('returns a CanceledError if cancellation has been requested', function() {
|
||||||
var cancel;
|
let cancel;
|
||||||
var token = new CancelToken(function(c) {
|
const token = new CancelToken(function(c) {
|
||||||
cancel = c;
|
cancel = c;
|
||||||
});
|
});
|
||||||
cancel('Operation has been canceled.');
|
cancel('Operation has been canceled.');
|
||||||
@@ -28,15 +28,15 @@ describe('CancelToken', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('returns undefined if cancellation has not been requested', function() {
|
it('returns undefined if cancellation has not been requested', function() {
|
||||||
var token = new CancelToken(function() {});
|
const token = new CancelToken(function() {});
|
||||||
expect(token.reason).toBeUndefined();
|
expect(token.reason).toBeUndefined();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('promise', function() {
|
describe('promise', function() {
|
||||||
it('returns a Promise that resolves when cancellation is requested', function(done) {
|
it('returns a Promise that resolves when cancellation is requested', function(done) {
|
||||||
var cancel;
|
let cancel;
|
||||||
var token = new CancelToken(function(c) {
|
const token = new CancelToken(function(c) {
|
||||||
cancel = c;
|
cancel = c;
|
||||||
});
|
});
|
||||||
token.promise.then(function onFulfilled(value) {
|
token.promise.then(function onFulfilled(value) {
|
||||||
@@ -51,8 +51,8 @@ describe('CancelToken', function() {
|
|||||||
describe('throwIfRequested', function() {
|
describe('throwIfRequested', function() {
|
||||||
it('throws if cancellation has been requested', function() {
|
it('throws if cancellation has been requested', function() {
|
||||||
// Note: we cannot use expect.toThrowError here as CanceledError does not inherit from Error
|
// Note: we cannot use expect.toThrowError here as CanceledError does not inherit from Error
|
||||||
var cancel;
|
let cancel;
|
||||||
var token = new CancelToken(function(c) {
|
const token = new CancelToken(function(c) {
|
||||||
cancel = c;
|
cancel = c;
|
||||||
});
|
});
|
||||||
cancel('Operation has been canceled.');
|
cancel('Operation has been canceled.');
|
||||||
@@ -68,14 +68,14 @@ describe('CancelToken', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('does not throw if cancellation has not been requested', function() {
|
it('does not throw if cancellation has not been requested', function() {
|
||||||
var token = new CancelToken(function() {});
|
const token = new CancelToken(function() {});
|
||||||
token.throwIfRequested();
|
token.throwIfRequested();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('source', function() {
|
describe('source', function() {
|
||||||
it('returns an object containing token and cancel function', function() {
|
it('returns an object containing token and cancel function', function() {
|
||||||
var source = CancelToken.source();
|
const source = CancelToken.source();
|
||||||
expect(source.token).toEqual(jasmine.any(CancelToken));
|
expect(source.token).toEqual(jasmine.any(CancelToken));
|
||||||
expect(source.cancel).toEqual(jasmine.any(Function));
|
expect(source.cancel).toEqual(jasmine.any(Function));
|
||||||
expect(source.token.reason).toBeUndefined();
|
expect(source.token.reason).toBeUndefined();
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
var CanceledError = require('../../../lib/cancel/CanceledError');
|
import CanceledError from '../../../lib/cancel/CanceledError';
|
||||||
|
|
||||||
describe('Cancel', function() {
|
describe('Cancel', function() {
|
||||||
describe('toString', function() {
|
describe('toString', function() {
|
||||||
it('returns correct result when message is not specified', function() {
|
it('returns correct result when message is not specified', function() {
|
||||||
var cancel = new CanceledError();
|
const cancel = new CanceledError();
|
||||||
expect(cancel.toString()).toBe('CanceledError: canceled');
|
expect(cancel.toString()).toBe('CanceledError: canceled');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('returns correct result when message is specified', function() {
|
it('returns correct result when message is specified', function() {
|
||||||
var cancel = new CanceledError('Operation has been canceled.');
|
const cancel = new CanceledError('Operation has been canceled.');
|
||||||
expect(cancel.toString()).toBe('CanceledError: Operation has been canceled.');
|
expect(cancel.toString()).toBe('CanceledError: Operation has been canceled.');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
var isCancel = require('../../../lib/cancel/isCancel');
|
import isCancel from '../../../lib/cancel/isCancel';
|
||||||
var CanceledError = require('../../../lib/cancel/CanceledError');
|
import CanceledError from '../../../lib/cancel/CanceledError';
|
||||||
|
|
||||||
describe('isCancel', function() {
|
describe('isCancel', function() {
|
||||||
it('returns true if value is a CanceledError', function() {
|
it('returns true if value is a CanceledError', function() {
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
var AxiosError = require('../../../lib/core/AxiosError');
|
import AxiosError from '../../../lib/core/AxiosError';
|
||||||
|
|
||||||
describe('core::AxiosError', function() {
|
describe('core::AxiosError', function() {
|
||||||
it('should create an Error with message, config, code, request, response, stack and isAxiosError', function() {
|
it('should create an Error with message, config, code, request, response, stack and isAxiosError', function() {
|
||||||
var request = { path: '/foo' };
|
const request = { path: '/foo' };
|
||||||
var response = { status: 200, data: { foo: 'bar' } };
|
const response = { status: 200, data: { foo: 'bar' } };
|
||||||
var error = new AxiosError('Boom!', 'ESOMETHING', { foo: 'bar' }, request, response);
|
const error = new AxiosError('Boom!', 'ESOMETHING', { foo: 'bar' }, request, response);
|
||||||
expect(error instanceof Error).toBe(true);
|
expect(error instanceof Error).toBe(true);
|
||||||
expect(error.message).toBe('Boom!');
|
expect(error.message).toBe('Boom!');
|
||||||
expect(error.config).toEqual({ foo: 'bar' });
|
expect(error.config).toEqual({ foo: 'bar' });
|
||||||
@@ -17,10 +17,10 @@ describe('core::AxiosError', function() {
|
|||||||
it('should create an Error that can be serialized to JSON', function() {
|
it('should create an Error that can be serialized to JSON', function() {
|
||||||
// Attempting to serialize request and response results in
|
// Attempting to serialize request and response results in
|
||||||
// TypeError: Converting circular structure to JSON
|
// TypeError: Converting circular structure to JSON
|
||||||
var request = { path: '/foo' };
|
const request = { path: '/foo' };
|
||||||
var response = { status: 200, data: { foo: 'bar' } };
|
const response = { status: 200, data: { foo: 'bar' } };
|
||||||
var error = new AxiosError('Boom!', 'ESOMETHING', { foo: 'bar' }, request, response);
|
const error = new AxiosError('Boom!', 'ESOMETHING', { foo: 'bar' }, request, response);
|
||||||
var json = error.toJSON();
|
const json = error.toJSON();
|
||||||
expect(json.message).toBe('Boom!');
|
expect(json.message).toBe('Boom!');
|
||||||
expect(json.config).toEqual({ foo: 'bar' });
|
expect(json.config).toEqual({ foo: 'bar' });
|
||||||
expect(json.code).toBe('ESOMETHING');
|
expect(json.code).toBe('ESOMETHING');
|
||||||
@@ -31,11 +31,11 @@ describe('core::AxiosError', function() {
|
|||||||
|
|
||||||
describe('core::createError.from', function() {
|
describe('core::createError.from', function() {
|
||||||
it('should add config, config, request and response to error', function() {
|
it('should add config, config, request and response to error', function() {
|
||||||
var error = new Error('Boom!');
|
const error = new Error('Boom!');
|
||||||
var request = { path: '/foo' };
|
const request = { path: '/foo' };
|
||||||
var response = { status: 200, data: { foo: 'bar' } };
|
const response = { status: 200, data: { foo: 'bar' } };
|
||||||
|
|
||||||
var axiosError = AxiosError.from(error, 'ESOMETHING', { foo: 'bar' }, request, response);
|
const axiosError = AxiosError.from(error, 'ESOMETHING', { foo: 'bar' }, request, response);
|
||||||
expect(axiosError.config).toEqual({ foo: 'bar' });
|
expect(axiosError.config).toEqual({ foo: 'bar' });
|
||||||
expect(axiosError.code).toBe('ESOMETHING');
|
expect(axiosError.code).toBe('ESOMETHING');
|
||||||
expect(axiosError.request).toBe(request);
|
expect(axiosError.request).toBe(request);
|
||||||
@@ -44,7 +44,7 @@ describe('core::AxiosError', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should return error', function() {
|
it('should return error', function() {
|
||||||
var error = new Error('Boom!');
|
const error = new Error('Boom!');
|
||||||
expect(AxiosError.from(error, 'ESOMETHING', { foo: 'bar' }) instanceof AxiosError).toBeTruthy();
|
expect(AxiosError.from(error, 'ESOMETHING', { foo: 'bar' }) instanceof AxiosError).toBeTruthy();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
var buildFullPath = require('../../../lib/core/buildFullPath');
|
import buildFullPath from '../../../lib/core/buildFullPath';
|
||||||
|
|
||||||
describe('helpers::buildFullPath', function () {
|
describe('helpers::buildFullPath', function () {
|
||||||
it('should combine URLs when the requestedURL is relative', function () {
|
it('should combine URLs when the requestedURL is relative', function () {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
var defaults = require('../../../lib/defaults');
|
import defaults from '../../../lib/defaults';
|
||||||
var mergeConfig = require('../../../lib/core/mergeConfig');
|
import mergeConfig from '../../../lib/core/mergeConfig';
|
||||||
|
|
||||||
describe('core::mergeConfig', function() {
|
describe('core::mergeConfig', function() {
|
||||||
it('should accept undefined for second argument', function() {
|
it('should accept undefined for second argument', function() {
|
||||||
@@ -11,19 +11,19 @@ describe('core::mergeConfig', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should not leave references', function() {
|
it('should not leave references', function() {
|
||||||
var merged = mergeConfig(defaults, {});
|
const merged = mergeConfig(defaults, {});
|
||||||
expect(merged).not.toBe(defaults);
|
expect(merged).not.toBe(defaults);
|
||||||
expect(merged.headers).not.toBe(defaults.headers);
|
expect(merged.headers).not.toBe(defaults.headers);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow setting request options', function() {
|
it('should allow setting request options', function() {
|
||||||
var config = {
|
const config = {
|
||||||
url: '__sample url__',
|
url: '__sample url__',
|
||||||
method: '__sample method__',
|
method: '__sample method__',
|
||||||
params: '__sample params__',
|
params: '__sample params__',
|
||||||
data: { foo: true }
|
data: { foo: true }
|
||||||
};
|
};
|
||||||
var merged = mergeConfig(defaults, config);
|
const merged = mergeConfig(defaults, config);
|
||||||
expect(merged.url).toEqual(config.url);
|
expect(merged.url).toEqual(config.url);
|
||||||
expect(merged.method).toEqual(config.method);
|
expect(merged.method).toEqual(config.method);
|
||||||
expect(merged.params).toEqual(config.params);
|
expect(merged.params).toEqual(config.params);
|
||||||
@@ -31,18 +31,18 @@ describe('core::mergeConfig', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should not inherit request options', function() {
|
it('should not inherit request options', function() {
|
||||||
var localDefaults = {
|
const localDefaults = {
|
||||||
method: '__sample method__',
|
method: '__sample method__',
|
||||||
data: { foo: true }
|
data: { foo: true }
|
||||||
};
|
};
|
||||||
var merged = mergeConfig(localDefaults, {});
|
const merged = mergeConfig(localDefaults, {});
|
||||||
expect(merged.method).toEqual(undefined);
|
expect(merged.method).toEqual(undefined);
|
||||||
expect(merged.data).toEqual(undefined);
|
expect(merged.data).toEqual(undefined);
|
||||||
});
|
});
|
||||||
|
|
||||||
['auth', 'headers', 'params', 'proxy'].forEach(function(key) {
|
['auth', 'headers', 'params', 'proxy'].forEach(function(key) {
|
||||||
it('should set new config for' + key + ' without default', function() {
|
it('should set new config for' + key + ' without default', function() {
|
||||||
var a = {}, b = {}, c = {}
|
const a = {}, b = {}, c = {};
|
||||||
a[key] = undefined
|
a[key] = undefined
|
||||||
b[key] = { user: 'foo', pass: 'test' }
|
b[key] = { user: 'foo', pass: 'test' }
|
||||||
c[key] = { user: 'foo', pass: 'test' }
|
c[key] = { user: 'foo', pass: 'test' }
|
||||||
@@ -51,7 +51,7 @@ describe('core::mergeConfig', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should merge ' + key + ' with defaults', function() {
|
it('should merge ' + key + ' with defaults', function() {
|
||||||
var a = {}, b = {}, c = {};
|
const a = {}, b = {}, c = {};
|
||||||
a[key] = { user: 'foo', pass: 'bar' };
|
a[key] = { user: 'foo', pass: 'bar' };
|
||||||
b[key] = { pass: 'test' };
|
b[key] = { pass: 'test' };
|
||||||
c[key] = { user: 'foo', pass: 'test' };
|
c[key] = { user: 'foo', pass: 'test' };
|
||||||
@@ -61,7 +61,7 @@ describe('core::mergeConfig', function() {
|
|||||||
|
|
||||||
it('should overwrite default ' + key + ' with a non-object value', function() {
|
it('should overwrite default ' + key + ' with a non-object value', function() {
|
||||||
[false, null, 123].forEach(function(value) {
|
[false, null, 123].forEach(function(value) {
|
||||||
var a = {}, b = {}, c = {};
|
const a = {}, b = {}, c = {};
|
||||||
a[key] = { user: 'foo', pass: 'test' };
|
a[key] = { user: 'foo', pass: 'test' };
|
||||||
b[key] = value;
|
b[key] = value;
|
||||||
c[key] = value;
|
c[key] = value;
|
||||||
@@ -72,22 +72,22 @@ describe('core::mergeConfig', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should allow setting other options', function() {
|
it('should allow setting other options', function() {
|
||||||
var merged = mergeConfig(defaults, { timeout: 123 });
|
const merged = mergeConfig(defaults, { timeout: 123 });
|
||||||
expect(merged.timeout).toEqual(123);
|
expect(merged.timeout).toEqual(123);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow setting custom options', function() {
|
it('should allow setting custom options', function() {
|
||||||
var merged = mergeConfig(defaults, { foo: 'bar' });
|
const merged = mergeConfig(defaults, { foo: 'bar' });
|
||||||
expect(merged.foo).toEqual('bar');
|
expect(merged.foo).toEqual('bar');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow setting custom default options', function() {
|
it('should allow setting custom default options', function() {
|
||||||
var merged = mergeConfig({ foo: 'bar' }, {});
|
const merged = mergeConfig({ foo: 'bar' }, {});
|
||||||
expect(merged.foo).toEqual('bar');
|
expect(merged.foo).toEqual('bar');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow merging custom objects in the config', function() {
|
it('should allow merging custom objects in the config', function() {
|
||||||
var merged = mergeConfig({
|
const merged = mergeConfig({
|
||||||
nestedConfig: {
|
nestedConfig: {
|
||||||
propertyOnDefaultConfig: true
|
propertyOnDefaultConfig: true
|
||||||
}
|
}
|
||||||
@@ -101,28 +101,28 @@ describe('core::mergeConfig', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('valueFromConfig2Keys', function() {
|
describe('valueFromConfig2Keys', function() {
|
||||||
var config1 = {url: '/foo', method: 'post', data: {a: 3}};
|
const config1 = {url: '/foo', method: 'post', data: {a: 3}};
|
||||||
|
|
||||||
it('should skip if config2 is undefined', function() {
|
it('should skip if config2 is undefined', function() {
|
||||||
expect(mergeConfig(config1, {})).toEqual({});
|
expect(mergeConfig(config1, {})).toEqual({});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should clone config2 if is plain object', function() {
|
it('should clone config2 if is plain object', function() {
|
||||||
var data = {a: 1, b: 2};
|
const data = {a: 1, b: 2};
|
||||||
var merged = mergeConfig(config1, {data: data});
|
const merged = mergeConfig(config1, {data: data});
|
||||||
expect(merged.data).toEqual(data);
|
expect(merged.data).toEqual(data);
|
||||||
expect(merged.data).not.toBe(data);
|
expect(merged.data).not.toBe(data);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should clone config2 if is array', function() {
|
it('should clone config2 if is array', function() {
|
||||||
var data = [1, 2, 3];
|
const data = [1, 2, 3];
|
||||||
var merged = mergeConfig(config1, {data: data});
|
const merged = mergeConfig(config1, {data: data});
|
||||||
expect(merged.data).toEqual(data);
|
expect(merged.data).toEqual(data);
|
||||||
expect(merged.data).not.toBe(data);
|
expect(merged.data).not.toBe(data);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should set as config2 in other cases', function() {
|
it('should set as config2 in other cases', function() {
|
||||||
var obj = Object.create({});
|
const obj = Object.create({});
|
||||||
expect(mergeConfig(config1, {data: 1}).data).toBe(1);
|
expect(mergeConfig(config1, {data: 1}).data).toBe(1);
|
||||||
expect(mergeConfig(config1, {data: 'str'}).data).toBe('str');
|
expect(mergeConfig(config1, {data: 'str'}).data).toBe('str');
|
||||||
expect(mergeConfig(config1, {data: obj}).data).toBe(obj);
|
expect(mergeConfig(config1, {data: obj}).data).toBe(obj);
|
||||||
@@ -141,24 +141,24 @@ describe('core::mergeConfig', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should clone config2 if is plain object', function() {
|
it('should clone config2 if is plain object', function() {
|
||||||
var config1 = {headers: [1, 2, 3]};
|
const config1 = {headers: [1, 2, 3]};
|
||||||
var config2 = {headers: {a: 1, b: 2}};
|
const config2 = {headers: {a: 1, b: 2}};
|
||||||
var merged = mergeConfig(config1, config2);
|
const merged = mergeConfig(config1, config2);
|
||||||
expect(merged.headers).toEqual(config2.headers);
|
expect(merged.headers).toEqual(config2.headers);
|
||||||
expect(merged.headers).not.toBe(config2.headers);
|
expect(merged.headers).not.toBe(config2.headers);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should clone config2 if is array', function() {
|
it('should clone config2 if is array', function() {
|
||||||
var config1 = {headers: {a: 1, b: 1}};
|
const config1 = {headers: {a: 1, b: 1}};
|
||||||
var config2 = {headers: [1, 2, 3]};
|
const config2 = {headers: [1, 2, 3]};
|
||||||
var merged = mergeConfig(config1, config2);
|
const merged = mergeConfig(config1, config2);
|
||||||
expect(merged.headers).toEqual(config2.headers);
|
expect(merged.headers).toEqual(config2.headers);
|
||||||
expect(merged.headers).not.toBe(config2.headers);
|
expect(merged.headers).not.toBe(config2.headers);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should set as config2 in other cases', function() {
|
it('should set as config2 in other cases', function() {
|
||||||
var config1 = {headers: {a: 1, b: 1}};
|
const config1 = {headers: {a: 1, b: 1}};
|
||||||
var obj = Object.create({});
|
const obj = Object.create({});
|
||||||
expect(mergeConfig(config1, {headers: 1}).headers).toBe(1);
|
expect(mergeConfig(config1, {headers: 1}).headers).toBe(1);
|
||||||
expect(mergeConfig(config1, {headers: 'str'}).headers).toBe('str');
|
expect(mergeConfig(config1, {headers: 'str'}).headers).toBe('str');
|
||||||
expect(mergeConfig(config1, {headers: obj}).headers).toBe(obj);
|
expect(mergeConfig(config1, {headers: obj}).headers).toBe(obj);
|
||||||
@@ -166,24 +166,24 @@ describe('core::mergeConfig', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should clone config1 if is plain object', function() {
|
it('should clone config1 if is plain object', function() {
|
||||||
var config1 = {headers: {a: 1, b: 2}};
|
const config1 = {headers: {a: 1, b: 2}};
|
||||||
var config2 = {};
|
const config2 = {};
|
||||||
var merged = mergeConfig(config1, config2);
|
const merged = mergeConfig(config1, config2);
|
||||||
expect(merged.headers).toEqual(config1.headers);
|
expect(merged.headers).toEqual(config1.headers);
|
||||||
expect(merged.headers).not.toBe(config1.headers);
|
expect(merged.headers).not.toBe(config1.headers);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should clone config1 if is array', function() {
|
it('should clone config1 if is array', function() {
|
||||||
var config1 = {headers: [1, 2, 3]};
|
const config1 = {headers: [1, 2, 3]};
|
||||||
var config2 = {};
|
const config2 = {};
|
||||||
var merged = mergeConfig(config1, config2);
|
const merged = mergeConfig(config1, config2);
|
||||||
expect(merged.headers).toEqual(config1.headers);
|
expect(merged.headers).toEqual(config1.headers);
|
||||||
expect(merged.headers).not.toBe(config1.headers);
|
expect(merged.headers).not.toBe(config1.headers);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should set as config1 in other cases', function() {
|
it('should set as config1 in other cases', function() {
|
||||||
var config2 = {};
|
const config2 = {};
|
||||||
var obj = Object.create({});
|
const obj = Object.create({});
|
||||||
expect(mergeConfig({headers: 1}, config2).headers).toBe(1);
|
expect(mergeConfig({headers: 1}, config2).headers).toBe(1);
|
||||||
expect(mergeConfig({headers: 'str'}, config2).headers).toBe('str');
|
expect(mergeConfig({headers: 'str'}, config2).headers).toBe('str');
|
||||||
expect(mergeConfig({headers: obj}, config2).headers).toBe(obj);
|
expect(mergeConfig({headers: obj}, config2).headers).toBe(obj);
|
||||||
@@ -197,24 +197,24 @@ describe('core::mergeConfig', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should clone config2 if both config1 and config2 are plain object', function() {
|
it('should clone config2 if both config1 and config2 are plain object', function() {
|
||||||
var config1 = {transformRequest: {a: 1, b: 1}};
|
const config1 = {transformRequest: {a: 1, b: 1}};
|
||||||
var config2 = {transformRequest: {b: 2, c: 2}};
|
const config2 = {transformRequest: {b: 2, c: 2}};
|
||||||
var merged = mergeConfig(config1, config2);
|
const merged = mergeConfig(config1, config2);
|
||||||
expect(merged.transformRequest).toEqual(config2.transformRequest);
|
expect(merged.transformRequest).toEqual(config2.transformRequest);
|
||||||
expect(merged.transformRequest).not.toBe(config2.transformRequest);
|
expect(merged.transformRequest).not.toBe(config2.transformRequest);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should clone config2 if is array', function() {
|
it('should clone config2 if is array', function() {
|
||||||
var config1 = {transformRequest: {a: 1, b: 1}};
|
const config1 = {transformRequest: {a: 1, b: 1}};
|
||||||
var config2 = {transformRequest: [1, 2, 3]};
|
const config2 = {transformRequest: [1, 2, 3]};
|
||||||
var merged = mergeConfig(config1, config2);
|
const merged = mergeConfig(config1, config2);
|
||||||
expect(merged.transformRequest).toEqual(config2.transformRequest);
|
expect(merged.transformRequest).toEqual(config2.transformRequest);
|
||||||
expect(merged.transformRequest).not.toBe(config2.transformRequest);
|
expect(merged.transformRequest).not.toBe(config2.transformRequest);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should set as config2 in other cases', function() {
|
it('should set as config2 in other cases', function() {
|
||||||
var config1 = {transformRequest: {a: 1, b: 1}};
|
const config1 = {transformRequest: {a: 1, b: 1}};
|
||||||
var obj = Object.create({});
|
const obj = Object.create({});
|
||||||
expect(mergeConfig(config1, {transformRequest: 1}).transformRequest).toBe(1);
|
expect(mergeConfig(config1, {transformRequest: 1}).transformRequest).toBe(1);
|
||||||
expect(mergeConfig(config1, {transformRequest: 'str'}).transformRequest).toBe('str');
|
expect(mergeConfig(config1, {transformRequest: 'str'}).transformRequest).toBe('str');
|
||||||
expect(mergeConfig(config1, {transformRequest: obj}).transformRequest).toBe(obj);
|
expect(mergeConfig(config1, {transformRequest: obj}).transformRequest).toBe(obj);
|
||||||
@@ -222,24 +222,24 @@ describe('core::mergeConfig', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should clone config1 if is plain object', function() {
|
it('should clone config1 if is plain object', function() {
|
||||||
var config1 = {transformRequest: {a: 1, b: 2}};
|
const config1 = {transformRequest: {a: 1, b: 2}};
|
||||||
var config2 = {};
|
const config2 = {};
|
||||||
var merged = mergeConfig(config1, config2);
|
const merged = mergeConfig(config1, config2);
|
||||||
expect(merged.transformRequest).toEqual(config1.transformRequest);
|
expect(merged.transformRequest).toEqual(config1.transformRequest);
|
||||||
expect(merged.transformRequest).not.toBe(config1.transformRequest);
|
expect(merged.transformRequest).not.toBe(config1.transformRequest);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should clone config1 if is array', function() {
|
it('should clone config1 if is array', function() {
|
||||||
var config1 = {transformRequest: [1, 2, 3]};
|
const config1 = {transformRequest: [1, 2, 3]};
|
||||||
var config2 = {};
|
const config2 = {};
|
||||||
var merged = mergeConfig(config1, config2);
|
const merged = mergeConfig(config1, config2);
|
||||||
expect(merged.transformRequest).toEqual(config1.transformRequest);
|
expect(merged.transformRequest).toEqual(config1.transformRequest);
|
||||||
expect(merged.transformRequest).not.toBe(config1.transformRequest);
|
expect(merged.transformRequest).not.toBe(config1.transformRequest);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should set as config1 in other cases', function() {
|
it('should set as config1 in other cases', function() {
|
||||||
var config2 = {};
|
const config2 = {};
|
||||||
var obj = Object.create({});
|
const obj = Object.create({});
|
||||||
expect(mergeConfig({transformRequest: 1}, config2).transformRequest).toBe(1);
|
expect(mergeConfig({transformRequest: 1}, config2).transformRequest).toBe(1);
|
||||||
expect(mergeConfig({transformRequest: 'str'}, config2).transformRequest).toBe('str');
|
expect(mergeConfig({transformRequest: 'str'}, config2).transformRequest).toBe('str');
|
||||||
expect(mergeConfig({transformRequest: obj}, config2).transformRequest).toBe(obj);
|
expect(mergeConfig({transformRequest: obj}, config2).transformRequest).toBe(obj);
|
||||||
@@ -258,24 +258,24 @@ describe('core::mergeConfig', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should clone config2 if is plain object', function() {
|
it('should clone config2 if is plain object', function() {
|
||||||
var config1 = {validateStatus: [1, 2, 3]};
|
const config1 = {validateStatus: [1, 2, 3]};
|
||||||
var config2 = {validateStatus: {a: 1, b: 2}};
|
const config2 = {validateStatus: {a: 1, b: 2}};
|
||||||
var merged = mergeConfig(config1, config2);
|
const merged = mergeConfig(config1, config2);
|
||||||
expect(merged.validateStatus).toEqual(config2.validateStatus);
|
expect(merged.validateStatus).toEqual(config2.validateStatus);
|
||||||
expect(merged.validateStatus).not.toBe(config2.validateStatus);
|
expect(merged.validateStatus).not.toBe(config2.validateStatus);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should clone config2 if is array', function() {
|
it('should clone config2 if is array', function() {
|
||||||
var config1 = {validateStatus: {a: 1, b: 2}};
|
const config1 = {validateStatus: {a: 1, b: 2}};
|
||||||
var config2 = {validateStatus: [1, 2, 3]};
|
const config2 = {validateStatus: [1, 2, 3]};
|
||||||
var merged = mergeConfig(config1, config2);
|
const merged = mergeConfig(config1, config2);
|
||||||
expect(merged.validateStatus).toEqual(config2.validateStatus);
|
expect(merged.validateStatus).toEqual(config2.validateStatus);
|
||||||
expect(merged.validateStatus).not.toBe(config2.validateStatus);
|
expect(merged.validateStatus).not.toBe(config2.validateStatus);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should set as config2 in other cases', function() {
|
it('should set as config2 in other cases', function() {
|
||||||
var config1 = {validateStatus: {a: 1, b: 2}};
|
const config1 = {validateStatus: {a: 1, b: 2}};
|
||||||
var obj = Object.create({});
|
const obj = Object.create({});
|
||||||
expect(mergeConfig(config1, {validateStatus: 1}).validateStatus).toBe(1);
|
expect(mergeConfig(config1, {validateStatus: 1}).validateStatus).toBe(1);
|
||||||
expect(mergeConfig(config1, {validateStatus: 'str'}).validateStatus).toBe('str');
|
expect(mergeConfig(config1, {validateStatus: 'str'}).validateStatus).toBe('str');
|
||||||
expect(mergeConfig(config1, {validateStatus: obj}).validateStatus).toBe(obj);
|
expect(mergeConfig(config1, {validateStatus: obj}).validateStatus).toBe(obj);
|
||||||
@@ -283,24 +283,24 @@ describe('core::mergeConfig', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should clone config1 if is plain object', function() {
|
it('should clone config1 if is plain object', function() {
|
||||||
var config1 = {validateStatus: {a: 1, b: 2}};
|
const config1 = {validateStatus: {a: 1, b: 2}};
|
||||||
var config2 = {};
|
const config2 = {};
|
||||||
var merged = mergeConfig(config1, config2);
|
const merged = mergeConfig(config1, config2);
|
||||||
expect(merged.validateStatus).toEqual(config1.validateStatus);
|
expect(merged.validateStatus).toEqual(config1.validateStatus);
|
||||||
expect(merged.validateStatus).not.toBe(config1.validateStatus);
|
expect(merged.validateStatus).not.toBe(config1.validateStatus);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should clone config1 if is array', function() {
|
it('should clone config1 if is array', function() {
|
||||||
var config1 = {validateStatus: [1, 2, 3]};
|
const config1 = {validateStatus: [1, 2, 3]};
|
||||||
var config2 = {};
|
const config2 = {};
|
||||||
var merged = mergeConfig(config1, config2);
|
const merged = mergeConfig(config1, config2);
|
||||||
expect(merged.validateStatus).toEqual(config1.validateStatus);
|
expect(merged.validateStatus).toEqual(config1.validateStatus);
|
||||||
expect(merged.validateStatus).not.toBe(config1.validateStatus);
|
expect(merged.validateStatus).not.toBe(config1.validateStatus);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should set as config1 in other cases', function() {
|
it('should set as config1 in other cases', function() {
|
||||||
var config2 = {};
|
const config2 = {};
|
||||||
var obj = Object.create({});
|
const obj = Object.create({});
|
||||||
expect(mergeConfig({validateStatus: 1}, config2).validateStatus).toBe(1);
|
expect(mergeConfig({validateStatus: 1}, config2).validateStatus).toBe(1);
|
||||||
expect(mergeConfig({validateStatus: 'str'}, config2).validateStatus).toBe('str');
|
expect(mergeConfig({validateStatus: 'str'}, config2).validateStatus).toBe('str');
|
||||||
expect(mergeConfig({validateStatus: obj}, config2).validateStatus).toBe(obj);
|
expect(mergeConfig({validateStatus: obj}, config2).validateStatus).toBe(obj);
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
var settle = require('../../../lib/core/settle');
|
import settle from '../../../lib/core/settle';
|
||||||
|
|
||||||
describe('core::settle', function() {
|
describe('core::settle', function() {
|
||||||
var resolve;
|
let resolve;
|
||||||
var reject;
|
let reject;
|
||||||
|
|
||||||
beforeEach(function() {
|
beforeEach(function() {
|
||||||
resolve = jasmine.createSpy('resolve');
|
resolve = jasmine.createSpy('resolve');
|
||||||
@@ -10,7 +10,7 @@ describe('core::settle', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should resolve promise if status is not set', function() {
|
it('should resolve promise if status is not set', function() {
|
||||||
var response = {
|
const response = {
|
||||||
config: {
|
config: {
|
||||||
validateStatus: function() {
|
validateStatus: function() {
|
||||||
return true;
|
return true;
|
||||||
@@ -23,7 +23,7 @@ describe('core::settle', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should resolve promise if validateStatus is not set', function() {
|
it('should resolve promise if validateStatus is not set', function() {
|
||||||
var response = {
|
const response = {
|
||||||
status: 500,
|
status: 500,
|
||||||
config: {
|
config: {
|
||||||
}
|
}
|
||||||
@@ -34,7 +34,7 @@ describe('core::settle', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should resolve promise if validateStatus returns true', function() {
|
it('should resolve promise if validateStatus returns true', function() {
|
||||||
var response = {
|
const response = {
|
||||||
status: 500,
|
status: 500,
|
||||||
config: {
|
config: {
|
||||||
validateStatus: function() {
|
validateStatus: function() {
|
||||||
@@ -48,10 +48,10 @@ describe('core::settle', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should reject promise if validateStatus returns false', function() {
|
it('should reject promise if validateStatus returns false', function() {
|
||||||
var req = {
|
const req = {
|
||||||
path: '/foo'
|
path: '/foo'
|
||||||
};
|
};
|
||||||
var response = {
|
const response = {
|
||||||
status: 500,
|
status: 500,
|
||||||
config: {
|
config: {
|
||||||
validateStatus: function() {
|
validateStatus: function() {
|
||||||
@@ -63,7 +63,7 @@ describe('core::settle', function() {
|
|||||||
settle(resolve, reject, response);
|
settle(resolve, reject, response);
|
||||||
expect(resolve).not.toHaveBeenCalled();
|
expect(resolve).not.toHaveBeenCalled();
|
||||||
expect(reject).toHaveBeenCalled();
|
expect(reject).toHaveBeenCalled();
|
||||||
var reason = reject.calls.first().args[0];
|
const reason = reject.calls.first().args[0];
|
||||||
expect(reason instanceof Error).toBe(true);
|
expect(reason instanceof Error).toBe(true);
|
||||||
expect(reason.message).toBe('Request failed with status code 500');
|
expect(reason.message).toBe('Request failed with status code 500');
|
||||||
expect(reason.config).toBe(response.config);
|
expect(reason.config).toBe(response.config);
|
||||||
@@ -72,8 +72,8 @@ describe('core::settle', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should pass status to validateStatus', function() {
|
it('should pass status to validateStatus', function() {
|
||||||
var validateStatus = jasmine.createSpy('validateStatus');
|
const validateStatus = jasmine.createSpy('validateStatus');
|
||||||
var response = {
|
const response = {
|
||||||
status: 500,
|
status: 500,
|
||||||
config: {
|
config: {
|
||||||
validateStatus: validateStatus
|
validateStatus: validateStatus
|
||||||
|
|||||||
@@ -1,19 +1,22 @@
|
|||||||
var transformData = require('../../../lib/core/transformData');
|
import transformData from '../../../lib/core/transformData';
|
||||||
|
|
||||||
describe('core::transformData', function () {
|
describe('core::transformData', function () {
|
||||||
it('should support a single transformer', function () {
|
it('should support a single transformer', function () {
|
||||||
var data;
|
let data;
|
||||||
data = transformData(data, null, null, function (data) {
|
|
||||||
|
data = transformData.call({
|
||||||
|
|
||||||
|
}, function (data) {
|
||||||
data = 'foo';
|
data = 'foo';
|
||||||
return data;
|
return data;
|
||||||
});
|
})
|
||||||
|
|
||||||
expect(data).toEqual('foo');
|
expect(data).toEqual('foo');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support an array of transformers', function () {
|
it('should support an array of transformers', function () {
|
||||||
var data = '';
|
let data = '';
|
||||||
data = transformData(data, null, null, [function (data) {
|
data = transformData.call({data}, [function (data) {
|
||||||
data += 'f';
|
data += 'f';
|
||||||
return data;
|
return data;
|
||||||
}, function (data) {
|
}, function (data) {
|
||||||
@@ -28,11 +31,11 @@ describe('core::transformData', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should support reference headers in transformData', function () {
|
it('should support reference headers in transformData', function () {
|
||||||
var headers = {
|
const headers = {
|
||||||
'content-type': 'foo/bar',
|
'content-type': 'foo/bar',
|
||||||
};
|
};
|
||||||
var data = '';
|
let data = '';
|
||||||
data = transformData(data, headers, null, [function (data, headers) {
|
data = transformData.call({data, headers}, [function (data, headers) {
|
||||||
data += headers['content-type'];
|
data += headers['content-type'];
|
||||||
return data;
|
return data;
|
||||||
}]);
|
}]);
|
||||||
@@ -41,11 +44,11 @@ describe('core::transformData', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should support reference status code in transformData', function () {
|
it('should support reference status code in transformData', function () {
|
||||||
var data = '';
|
let data = '';
|
||||||
data = transformData(data, null, 200, [function (data, headers, status) {
|
data = transformData.call({}, [function (data, headers, status) {
|
||||||
data += status;
|
data += status;
|
||||||
return data;
|
return data;
|
||||||
}]);
|
}], {data, status: 200});
|
||||||
|
|
||||||
expect(data).toEqual('200');
|
expect(data).toEqual('200');
|
||||||
});
|
});
|
||||||
|
|||||||
+17
-16
@@ -1,8 +1,9 @@
|
|||||||
var defaults = require('../../lib/defaults');
|
import defaults from '../../lib/defaults';
|
||||||
var utils = require('../../lib/utils');
|
import utils from '../../lib/utils';
|
||||||
|
import AxiosHeaders from '../../lib/core/AxiosHeaders';
|
||||||
|
|
||||||
describe('defaults', function () {
|
describe('defaults', function () {
|
||||||
var XSRF_COOKIE_NAME = 'CUSTOM-XSRF-TOKEN';
|
const XSRF_COOKIE_NAME = 'CUSTOM-XSRF-TOKEN';
|
||||||
|
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
jasmine.Ajax.install();
|
jasmine.Ajax.install();
|
||||||
@@ -17,13 +18,13 @@ describe('defaults', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should transform request json', function () {
|
it('should transform request json', function () {
|
||||||
expect(defaults.transformRequest[0]({foo: 'bar'})).toEqual('{"foo":"bar"}');
|
expect(defaults.transformRequest[0]({foo: 'bar'}, new AxiosHeaders())).toEqual('{"foo":"bar"}');
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should also transform request json when 'Content-Type' is 'application/json'", function () {
|
it("should also transform request json when 'Content-Type' is 'application/json'", function () {
|
||||||
var headers = {
|
const headers = new AxiosHeaders({
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
};
|
});
|
||||||
expect(defaults.transformRequest[0](JSON.stringify({ foo: 'bar' }), headers)).toEqual('{"foo":"bar"}');
|
expect(defaults.transformRequest[0](JSON.stringify({ foo: 'bar' }), headers)).toEqual('{"foo":"bar"}');
|
||||||
expect(defaults.transformRequest[0]([42, 43], headers)).toEqual('[42,43]');
|
expect(defaults.transformRequest[0]([42, 43], headers)).toEqual('[42,43]');
|
||||||
expect(defaults.transformRequest[0]('foo', headers)).toEqual('"foo"');
|
expect(defaults.transformRequest[0]('foo', headers)).toEqual('"foo"');
|
||||||
@@ -34,23 +35,23 @@ describe('defaults', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("should transform the plain data object to a FormData instance 'Content-Type' if header is 'multipart/form-data'", function() {
|
it("should transform the plain data object to a FormData instance 'Content-Type' if header is 'multipart/form-data'", function() {
|
||||||
var headers = {
|
const headers = new AxiosHeaders({
|
||||||
'Content-Type': 'multipart/form-data'
|
'Content-Type': 'multipart/form-data'
|
||||||
};
|
});
|
||||||
|
|
||||||
var payload = {x: 1};
|
const payload = {x: 1};
|
||||||
|
|
||||||
var transformed = defaults.transformRequest[0](payload, headers);
|
const transformed = defaults.transformRequest[0](payload, headers);
|
||||||
|
|
||||||
expect(transformed).toEqual(jasmine.any(FormData));
|
expect(transformed).toEqual(jasmine.any(FormData));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should do nothing to request string', function () {
|
it('should do nothing to request string', function () {
|
||||||
expect(defaults.transformRequest[0]('foo=bar')).toEqual('foo=bar');
|
expect(defaults.transformRequest[0]('foo=bar', new AxiosHeaders())).toEqual('foo=bar');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should transform response json', function () {
|
it('should transform response json', function () {
|
||||||
var data = defaults.transformResponse[0].call(defaults, '{"foo":"bar"}');
|
const data = defaults.transformResponse[0].call(defaults, '{"foo":"bar"}');
|
||||||
|
|
||||||
expect(typeof data).toEqual('object');
|
expect(typeof data).toEqual('object');
|
||||||
expect(data.foo).toEqual('bar');
|
expect(data.foo).toEqual('bar');
|
||||||
@@ -92,7 +93,7 @@ describe('defaults', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should use default config for custom instance', function (done) {
|
it('should use default config for custom instance', function (done) {
|
||||||
var instance = axios.create({
|
const instance = axios.create({
|
||||||
xsrfCookieName: XSRF_COOKIE_NAME,
|
xsrfCookieName: XSRF_COOKIE_NAME,
|
||||||
xsrfHeaderName: 'X-CUSTOM-XSRF-TOKEN'
|
xsrfHeaderName: 'X-CUSTOM-XSRF-TOKEN'
|
||||||
});
|
});
|
||||||
@@ -127,7 +128,7 @@ describe('defaults', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should use header config', function (done) {
|
it('should use header config', function (done) {
|
||||||
var instance = axios.create({
|
const instance = axios.create({
|
||||||
headers: {
|
headers: {
|
||||||
common: {
|
common: {
|
||||||
'X-COMMON-HEADER': 'commonHeaderValue'
|
'X-COMMON-HEADER': 'commonHeaderValue'
|
||||||
@@ -163,7 +164,7 @@ describe('defaults', function () {
|
|||||||
|
|
||||||
it('should be used by custom instance if set before instance created', function (done) {
|
it('should be used by custom instance if set before instance created', function (done) {
|
||||||
axios.defaults.baseURL = 'http://example.org/';
|
axios.defaults.baseURL = 'http://example.org/';
|
||||||
var instance = axios.create();
|
const instance = axios.create();
|
||||||
|
|
||||||
instance.get('/foo');
|
instance.get('/foo');
|
||||||
|
|
||||||
@@ -174,7 +175,7 @@ describe('defaults', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should not be used by custom instance if set after instance created', function (done) {
|
it('should not be used by custom instance if set after instance created', function (done) {
|
||||||
var instance = axios.create();
|
const instance = axios.create();
|
||||||
axios.defaults.baseURL = 'http://example.org/';
|
axios.defaults.baseURL = 'http://example.org/';
|
||||||
|
|
||||||
instance.get('/foo');
|
instance.get('/foo');
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
function testHeaderValue(headers, key, val) {
|
function testHeaderValue(headers, key, val) {
|
||||||
var found = false;
|
let found = false;
|
||||||
|
|
||||||
for (var k in headers) {
|
for (const k in headers) {
|
||||||
if (k.toLowerCase() === key.toLowerCase()) {
|
if (k.toLowerCase() === key.toLowerCase()) {
|
||||||
found = true;
|
found = true;
|
||||||
expect(headers[k]).toEqual(val);
|
expect(headers[k]).toEqual(val);
|
||||||
@@ -28,12 +28,12 @@ describe('headers', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should default common headers', function (done) {
|
it('should default common headers', function (done) {
|
||||||
var headers = axios.defaults.headers.common;
|
const headers = axios.defaults.headers.common;
|
||||||
|
|
||||||
axios('/foo');
|
axios('/foo');
|
||||||
|
|
||||||
getAjaxRequest().then(function (request) {
|
getAjaxRequest().then(function (request) {
|
||||||
for (var key in headers) {
|
for (const key in headers) {
|
||||||
if (headers.hasOwnProperty(key)) {
|
if (headers.hasOwnProperty(key)) {
|
||||||
expect(request.requestHeaders[key]).toEqual(headers[key]);
|
expect(request.requestHeaders[key]).toEqual(headers[key]);
|
||||||
}
|
}
|
||||||
@@ -43,12 +43,12 @@ describe('headers', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should add extra headers for post', function (done) {
|
it('should add extra headers for post', function (done) {
|
||||||
var headers = axios.defaults.headers.common;
|
const headers = axios.defaults.headers.common;
|
||||||
|
|
||||||
axios.post('/foo', 'fizz=buzz');
|
axios.post('/foo', 'fizz=buzz');
|
||||||
|
|
||||||
getAjaxRequest().then(function (request) {
|
getAjaxRequest().then(function (request) {
|
||||||
for (var key in headers) {
|
for (const key in headers) {
|
||||||
if (headers.hasOwnProperty(key)) {
|
if (headers.hasOwnProperty(key)) {
|
||||||
expect(request.requestHeaders[key]).toEqual(headers[key]);
|
expect(request.requestHeaders[key]).toEqual(headers[key]);
|
||||||
}
|
}
|
||||||
@@ -72,15 +72,17 @@ describe('headers', function () {
|
|||||||
'x-header-a': null,
|
'x-header-a': null,
|
||||||
'x-header-b': undefined
|
'x-header-b': undefined
|
||||||
}
|
}
|
||||||
|
}).catch(function (err) {
|
||||||
|
done(err);
|
||||||
});
|
});
|
||||||
|
|
||||||
getAjaxRequest().then(function (request) {
|
getAjaxRequest().then(function (request) {
|
||||||
testHeaderValue(request.requestHeaders, 'Content-Type', null);
|
testHeaderValue(request.requestHeaders, 'Content-Type', undefined);
|
||||||
testHeaderValue(request.requestHeaders, 'x-header-a', null);
|
testHeaderValue(request.requestHeaders, 'x-header-a', undefined);
|
||||||
testHeaderValue(request.requestHeaders, 'x-header-b', undefined);
|
testHeaderValue(request.requestHeaders, 'x-header-b', undefined);
|
||||||
testHeaderValue(request.requestHeaders, 'x-header-c', 'c');
|
testHeaderValue(request.requestHeaders, 'x-header-c', 'c');
|
||||||
done();
|
done();
|
||||||
});
|
}).catch(done);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should use application/json when posting an object', function (done) {
|
it('should use application/json when posting an object', function (done) {
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
var bind = require('../../../lib/helpers/bind');
|
import bind from '../../../lib/helpers/bind';
|
||||||
|
|
||||||
describe('bind', function () {
|
describe('bind', function () {
|
||||||
it('should bind an object to a function', function () {
|
it('should bind an object to a function', function () {
|
||||||
var o = { val: 123 };
|
const o = { val: 123 };
|
||||||
var f = bind(function (num) {
|
const f = bind(function (num) {
|
||||||
return this.val * num;
|
return this.val * num;
|
||||||
}, o);
|
}, o);
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
var buildURL = require('../../../lib/helpers/buildURL');
|
import buildURL from '../../../lib/helpers/buildURL';
|
||||||
var URLSearchParams = require('url-search-params');
|
import URLSearchParams from 'url-search-params';
|
||||||
|
|
||||||
describe('helpers::buildURL', function () {
|
describe('helpers::buildURL', function () {
|
||||||
it('should support null params', function () {
|
it('should support null params', function () {
|
||||||
@@ -21,7 +21,7 @@ describe('helpers::buildURL', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should support date params', function () {
|
it('should support date params', function () {
|
||||||
var date = new Date();
|
const date = new Date();
|
||||||
|
|
||||||
expect(buildURL('/foo', {
|
expect(buildURL('/foo', {
|
||||||
date: date
|
date: date
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
var combineURLs = require('../../../lib/helpers/combineURLs');
|
import combineURLs from '../../../lib/helpers/combineURLs';
|
||||||
|
|
||||||
describe('helpers::combineURLs', function () {
|
describe('helpers::combineURLs', function () {
|
||||||
it('should combine URLs', function () {
|
it('should combine URLs', function () {
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
var cookies = require('../../../lib/helpers/cookies');
|
import cookies from '../../../lib/helpers/cookies';
|
||||||
|
|
||||||
describe('helpers::cookies', function () {
|
describe('helpers::cookies', function () {
|
||||||
afterEach(function () {
|
afterEach(function () {
|
||||||
// Remove all the cookies
|
// Remove all the cookies
|
||||||
var expires = Date.now() - (60 * 60 * 24 * 7);
|
const expires = Date.now() - (60 * 60 * 24 * 7);
|
||||||
document.cookie.split(';').map(function (cookie) {
|
document.cookie.split(';').map(function (cookie) {
|
||||||
return cookie.split('=')[0];
|
return cookie.split('=')[0];
|
||||||
}).forEach(function (name) {
|
}).forEach(function (name) {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
var formDataToJSON = require('../../../lib/helpers/formDataToJSON');
|
import formDataToJSON from '../../../lib/helpers/formDataToJSON';
|
||||||
|
|
||||||
describe('formDataToJSON', function () {
|
describe('formDataToJSON', function () {
|
||||||
it('should convert a FormData Object to JSON Object', function () {
|
it('should convert a FormData Object to JSON Object', function () {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
var isAbsoluteURL = require('../../../lib/helpers/isAbsoluteURL');
|
import isAbsoluteURL from '../../../lib/helpers/isAbsoluteURL';
|
||||||
|
|
||||||
describe('helpers::isAbsoluteURL', function () {
|
describe('helpers::isAbsoluteURL', function () {
|
||||||
it('should return true if URL begins with valid scheme name', function () {
|
it('should return true if URL begins with valid scheme name', function () {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
var AxiosError = require('../../../lib/core/AxiosError');
|
import AxiosError from '../../../lib/core/AxiosError';
|
||||||
var isAxiosError = require('../../../lib/helpers/isAxiosError');
|
import isAxiosError from '../../../lib/helpers/isAxiosError';
|
||||||
|
|
||||||
describe('helpers::isAxiosError', function() {
|
describe('helpers::isAxiosError', function() {
|
||||||
it('should return true if the error is created by core::createError', function() {
|
it('should return true if the error is created by core::createError', function() {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
var isURLSameOrigin = require('../../../lib/helpers/isURLSameOrigin');
|
import isURLSameOrigin from '../../../lib/helpers/isURLSameOrigin';
|
||||||
|
|
||||||
describe('helpers::isURLSameOrigin', function () {
|
describe('helpers::isURLSameOrigin', function () {
|
||||||
it('should detect same origin', function () {
|
it('should detect same origin', function () {
|
||||||
|
|||||||
@@ -1,21 +0,0 @@
|
|||||||
var normalizeHeaderName = require('../../../lib/helpers/normalizeHeaderName');
|
|
||||||
|
|
||||||
describe('helpers::normalizeHeaderName', function () {
|
|
||||||
it('should normalize matching header name', function () {
|
|
||||||
var headers = {
|
|
||||||
'conTenT-Type': 'foo/bar',
|
|
||||||
};
|
|
||||||
normalizeHeaderName(headers, 'Content-Type');
|
|
||||||
expect(headers['Content-Type']).toBe('foo/bar');
|
|
||||||
expect(headers['conTenT-Type']).toBeUndefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should not change non-matching header name', function () {
|
|
||||||
var headers = {
|
|
||||||
'content-type': 'foo/bar',
|
|
||||||
};
|
|
||||||
normalizeHeaderName(headers, 'Content-Length');
|
|
||||||
expect(headers['content-type']).toBe('foo/bar');
|
|
||||||
expect(headers['Content-Length']).toBeUndefined();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
var parseHeaders = require('../../../lib/helpers/parseHeaders');
|
import parseHeaders from '../../../lib/helpers/parseHeaders';
|
||||||
|
|
||||||
describe('helpers::parseHeaders', function () {
|
describe('helpers::parseHeaders', function () {
|
||||||
it('should parse headers', function () {
|
it('should parse headers', function () {
|
||||||
var date = new Date();
|
const date = new Date();
|
||||||
var parsed = parseHeaders(
|
const parsed = parseHeaders(
|
||||||
'Date: ' + date.toISOString() + '\n' +
|
'Date: ' + date.toISOString() + '\n' +
|
||||||
'Content-Type: application/json\n' +
|
'Content-Type: application/json\n' +
|
||||||
'Connection: keep-alive\n' +
|
'Connection: keep-alive\n' +
|
||||||
@@ -17,11 +17,11 @@ describe('helpers::parseHeaders', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should use array for set-cookie', function() {
|
it('should use array for set-cookie', function() {
|
||||||
var parsedZero = parseHeaders('');
|
const parsedZero = parseHeaders('');
|
||||||
var parsedSingle = parseHeaders(
|
const parsedSingle = parseHeaders(
|
||||||
'Set-Cookie: key=val;'
|
'Set-Cookie: key=val;'
|
||||||
);
|
);
|
||||||
var parsedMulti = parseHeaders(
|
const parsedMulti = parseHeaders(
|
||||||
'Set-Cookie: key=val;\n' +
|
'Set-Cookie: key=val;\n' +
|
||||||
'Set-Cookie: key2=val2;\n'
|
'Set-Cookie: key2=val2;\n'
|
||||||
);
|
);
|
||||||
@@ -32,7 +32,7 @@ describe('helpers::parseHeaders', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should handle duplicates', function() {
|
it('should handle duplicates', function() {
|
||||||
var parsed = parseHeaders(
|
const parsed = parseHeaders(
|
||||||
'Age: age-a\n' + // age is in ignore duplicates blocklist
|
'Age: age-a\n' + // age is in ignore duplicates blocklist
|
||||||
'Age: age-b\n' +
|
'Age: age-b\n' +
|
||||||
'Foo: foo-a\n' +
|
'Foo: foo-a\n' +
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
var spread = require('../../../lib/helpers/spread');
|
import spread from '../../../lib/helpers/spread';
|
||||||
|
|
||||||
describe('helpers::spread', function () {
|
describe('helpers::spread', function () {
|
||||||
it('should spread array to arguments', function () {
|
it('should spread array to arguments', function () {
|
||||||
var value = 0;
|
let value = 0;
|
||||||
spread(function (a, b) {
|
spread(function (a, b) {
|
||||||
value = a * b;
|
value = a * b;
|
||||||
})([5, 10]);
|
})([5, 10]);
|
||||||
@@ -11,7 +11,7 @@ describe('helpers::spread', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should return callback result', function () {
|
it('should return callback result', function () {
|
||||||
var value = spread(function (a, b) {
|
const value = spread(function (a, b) {
|
||||||
return a * b;
|
return a * b;
|
||||||
})([5, 10]);
|
})([5, 10]);
|
||||||
|
|
||||||
|
|||||||
@@ -1,15 +1,15 @@
|
|||||||
var toFormData = require('../../../lib/helpers/toFormData');
|
import toFormData from '../../../lib/helpers/toFormData';
|
||||||
|
|
||||||
describe('toFormData', function () {
|
describe('toFormData', function () {
|
||||||
it('should convert nested data object to FormData with dots option enabled', function () {
|
it('should convert nested data object to FormData with dots option enabled', function () {
|
||||||
var o = {
|
const o = {
|
||||||
val: 123,
|
val: 123,
|
||||||
nested: {
|
nested: {
|
||||||
arr: ['hello', 'world']
|
arr: ['hello', 'world']
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
var form = toFormData(o, null, {dots: true});
|
const form = toFormData(o, null, {dots: true});
|
||||||
expect(form instanceof FormData).toEqual(true);
|
expect(form instanceof FormData).toEqual(true);
|
||||||
expect(Array.from(form.keys()).length).toEqual(3);
|
expect(Array.from(form.keys()).length).toEqual(3);
|
||||||
expect(form.get('val')).toEqual('123');
|
expect(form.get('val')).toEqual('123');
|
||||||
@@ -17,13 +17,13 @@ describe('toFormData', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should respect metaTokens option', function () {
|
it('should respect metaTokens option', function () {
|
||||||
var data = {
|
const data = {
|
||||||
'obj{}': {x: 1, y: 2}
|
'obj{}': {x: 1, y: 2}
|
||||||
};
|
};
|
||||||
|
|
||||||
var str = JSON.stringify(data['obj{}']);
|
const str = JSON.stringify(data['obj{}']);
|
||||||
|
|
||||||
var form = toFormData(data, null, {metaTokens: false});
|
const form = toFormData(data, null, {metaTokens: false});
|
||||||
|
|
||||||
expect(Array.from(form.keys()).length).toEqual(1);
|
expect(Array.from(form.keys()).length).toEqual(1);
|
||||||
expect(form.getAll('obj')).toEqual([str]);
|
expect(form.getAll('obj')).toEqual([str]);
|
||||||
@@ -31,12 +31,12 @@ describe('toFormData', function () {
|
|||||||
|
|
||||||
describe('Flat arrays serialization', function () {
|
describe('Flat arrays serialization', function () {
|
||||||
it('should include full indexes when the `indexes` option is set to true', function () {
|
it('should include full indexes when the `indexes` option is set to true', function () {
|
||||||
var data = {
|
const data = {
|
||||||
arr: [1, 2, 3],
|
arr: [1, 2, 3],
|
||||||
arr2: [1, [2], 3]
|
arr2: [1, [2], 3]
|
||||||
};
|
};
|
||||||
|
|
||||||
var form = toFormData(data, null, {indexes: true});
|
const form = toFormData(data, null, {indexes: true});
|
||||||
|
|
||||||
expect(Array.from(form.keys()).length).toEqual(6);
|
expect(Array.from(form.keys()).length).toEqual(6);
|
||||||
|
|
||||||
@@ -50,12 +50,12 @@ describe('toFormData', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should include brackets only when the `indexes` option is set to false', function () {
|
it('should include brackets only when the `indexes` option is set to false', function () {
|
||||||
var data = {
|
const data = {
|
||||||
arr: [1, 2, 3],
|
arr: [1, 2, 3],
|
||||||
arr2: [1, [2], 3]
|
arr2: [1, [2], 3]
|
||||||
};
|
};
|
||||||
|
|
||||||
var form = toFormData(data, null, {indexes: false});
|
const form = toFormData(data, null, {indexes: false});
|
||||||
|
|
||||||
expect(Array.from(form.keys()).length).toEqual(6);
|
expect(Array.from(form.keys()).length).toEqual(6);
|
||||||
|
|
||||||
@@ -67,12 +67,12 @@ describe('toFormData', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should omit brackets when the `indexes` option is set to null', function () {
|
it('should omit brackets when the `indexes` option is set to null', function () {
|
||||||
var data = {
|
const data = {
|
||||||
arr: [1, 2, 3],
|
arr: [1, 2, 3],
|
||||||
arr2: [1, [2], 3]
|
arr2: [1, [2], 3]
|
||||||
};
|
};
|
||||||
|
|
||||||
var form = toFormData(data, null, {indexes: null});
|
const form = toFormData(data, null, {indexes: null});
|
||||||
|
|
||||||
expect(Array.from(form.keys()).length).toEqual(6);
|
expect(Array.from(form.keys()).length).toEqual(6);
|
||||||
|
|
||||||
@@ -85,14 +85,14 @@ describe('toFormData', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should convert nested data object to FormData', function () {
|
it('should convert nested data object to FormData', function () {
|
||||||
var o = {
|
const o = {
|
||||||
val: 123,
|
val: 123,
|
||||||
nested: {
|
nested: {
|
||||||
arr: ['hello', 'world']
|
arr: ['hello', 'world']
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
var form = toFormData(o);
|
const form = toFormData(o);
|
||||||
expect(form instanceof FormData).toEqual(true);
|
expect(form instanceof FormData).toEqual(true);
|
||||||
expect(Array.from(form.keys()).length).toEqual(3);
|
expect(Array.from(form.keys()).length).toEqual(3);
|
||||||
expect(form.get('val')).toEqual('123');
|
expect(form.get('val')).toEqual('123');
|
||||||
@@ -100,24 +100,24 @@ describe('toFormData', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should append value whose key ends with [] as separate values with the same key', function () {
|
it('should append value whose key ends with [] as separate values with the same key', function () {
|
||||||
var data = {
|
const data = {
|
||||||
'arr[]': [1, 2, 3]
|
'arr[]': [1, 2, 3]
|
||||||
};
|
};
|
||||||
|
|
||||||
var form = toFormData(data);
|
const form = toFormData(data);
|
||||||
|
|
||||||
expect(Array.from(form.keys()).length).toEqual(3);
|
expect(Array.from(form.keys()).length).toEqual(3);
|
||||||
expect(form.getAll('arr[]')).toEqual(['1', '2', '3']);
|
expect(form.getAll('arr[]')).toEqual(['1', '2', '3']);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should append value whose key ends with {} as a JSON string', function () {
|
it('should append value whose key ends with {} as a JSON string', function () {
|
||||||
var data = {
|
const data = {
|
||||||
'obj{}': {x: 1, y: 2}
|
'obj{}': {x: 1, y: 2}
|
||||||
};
|
};
|
||||||
|
|
||||||
var str = JSON.stringify(data['obj{}']);
|
const str = JSON.stringify(data['obj{}']);
|
||||||
|
|
||||||
var form = toFormData(data);
|
const form = toFormData(data);
|
||||||
|
|
||||||
expect(Array.from(form.keys()).length).toEqual(1);
|
expect(Array.from(form.keys()).length).toEqual(1);
|
||||||
expect(form.getAll('obj{}')).toEqual([str]);
|
expect(form.getAll('obj{}')).toEqual([str]);
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var validator = require('../../../lib/helpers/validator');
|
import validator from '../../../lib/helpers/validator';
|
||||||
|
|
||||||
describe('validator::assertOptions', function() {
|
describe('validator::assertOptions', function() {
|
||||||
it('should throw only if unknown an option was passed', function() {
|
it('should throw only if unknown an option was passed', function() {
|
||||||
|
|||||||
+15
-15
@@ -8,9 +8,9 @@ describe('instance', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should have the same methods as default instance', function () {
|
it('should have the same methods as default instance', function () {
|
||||||
var instance = axios.create();
|
const instance = axios.create();
|
||||||
|
|
||||||
for (var prop in axios) {
|
for (const prop in axios) {
|
||||||
if ([
|
if ([
|
||||||
'Axios',
|
'Axios',
|
||||||
'AxiosError',
|
'AxiosError',
|
||||||
@@ -35,7 +35,7 @@ describe('instance', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should make an http request without verb helper', function (done) {
|
it('should make an http request without verb helper', function (done) {
|
||||||
var instance = axios.create();
|
const instance = axios.create();
|
||||||
|
|
||||||
instance('/foo');
|
instance('/foo');
|
||||||
|
|
||||||
@@ -46,7 +46,7 @@ describe('instance', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should make an http request with url instead of baseURL', function (done) {
|
it('should make an http request with url instead of baseURL', function (done) {
|
||||||
var instance = axios.create({
|
const instance = axios.create({
|
||||||
url: 'https://api.example.com'
|
url: 'https://api.example.com'
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -59,7 +59,7 @@ describe('instance', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should make an http request', function (done) {
|
it('should make an http request', function (done) {
|
||||||
var instance = axios.create();
|
const instance = axios.create();
|
||||||
|
|
||||||
instance.get('/foo');
|
instance.get('/foo');
|
||||||
|
|
||||||
@@ -70,7 +70,7 @@ describe('instance', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should use instance options', function (done) {
|
it('should use instance options', function (done) {
|
||||||
var instance = axios.create({ timeout: 1000 });
|
const instance = axios.create({ timeout: 1000 });
|
||||||
|
|
||||||
instance.get('/foo');
|
instance.get('/foo');
|
||||||
|
|
||||||
@@ -81,7 +81,7 @@ describe('instance', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should have defaults.headers', function () {
|
it('should have defaults.headers', function () {
|
||||||
var instance = axios.create({
|
const instance = axios.create({
|
||||||
baseURL: 'https://api.example.com'
|
baseURL: 'https://api.example.com'
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -95,13 +95,13 @@ describe('instance', function () {
|
|||||||
return config;
|
return config;
|
||||||
});
|
});
|
||||||
|
|
||||||
var instance = axios.create();
|
const instance = axios.create();
|
||||||
instance.interceptors.request.use(function (config) {
|
instance.interceptors.request.use(function (config) {
|
||||||
config.bar = true;
|
config.bar = true;
|
||||||
return config;
|
return config;
|
||||||
});
|
});
|
||||||
|
|
||||||
var response;
|
let response;
|
||||||
instance.get('/foo').then(function (res) {
|
instance.get('/foo').then(function (res) {
|
||||||
response = res;
|
response = res;
|
||||||
});
|
});
|
||||||
@@ -120,10 +120,10 @@ describe('instance', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should have getUri on the instance', function() {
|
it('should have getUri on the instance', function() {
|
||||||
var instance = axios.create({
|
const instance = axios.create({
|
||||||
baseURL: 'https://api.example.com'
|
baseURL: 'https://api.example.com'
|
||||||
});
|
});
|
||||||
var options = {
|
const options = {
|
||||||
url: 'foo/bar',
|
url: 'foo/bar',
|
||||||
params: {
|
params: {
|
||||||
name: 'axios'
|
name: 'axios'
|
||||||
@@ -133,8 +133,8 @@ describe('instance', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should correctly build url without baseURL', function () {
|
it('should correctly build url without baseURL', function () {
|
||||||
var instance = axios.create();
|
const instance = axios.create();
|
||||||
var options = {
|
const options = {
|
||||||
url: 'foo/bar?foo=bar',
|
url: 'foo/bar?foo=bar',
|
||||||
params: {
|
params: {
|
||||||
name: 'axios'
|
name: 'axios'
|
||||||
@@ -144,8 +144,8 @@ describe('instance', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should correctly discard url hash mark', function () {
|
it('should correctly discard url hash mark', function () {
|
||||||
var instance = axios.create();
|
const instance = axios.create();
|
||||||
var options = {
|
const options = {
|
||||||
baseURL: 'https://api.example.com',
|
baseURL: 'https://api.example.com',
|
||||||
url: 'foo/bar?foo=bar#hash',
|
url: 'foo/bar?foo=bar#hash',
|
||||||
params: {
|
params: {
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ describe('interceptors', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should add a request interceptor (asynchronous by default)', function (done) {
|
it('should add a request interceptor (asynchronous by default)', function (done) {
|
||||||
var asyncFlag = false;
|
let asyncFlag = false;
|
||||||
axios.interceptors.request.use(function (config) {
|
axios.interceptors.request.use(function (config) {
|
||||||
config.headers.test = 'added by interceptor';
|
config.headers.test = 'added by interceptor';
|
||||||
expect(asyncFlag).toBe(true);
|
expect(asyncFlag).toBe(true);
|
||||||
@@ -27,7 +27,7 @@ describe('interceptors', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should add a request interceptor (explicitly flagged as asynchronous)', function (done) {
|
it('should add a request interceptor (explicitly flagged as asynchronous)', function (done) {
|
||||||
var asyncFlag = false;
|
let asyncFlag = false;
|
||||||
axios.interceptors.request.use(function (config) {
|
axios.interceptors.request.use(function (config) {
|
||||||
config.headers.test = 'added by interceptor';
|
config.headers.test = 'added by interceptor';
|
||||||
expect(asyncFlag).toBe(true);
|
expect(asyncFlag).toBe(true);
|
||||||
@@ -44,7 +44,7 @@ describe('interceptors', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should add a request interceptor that is executed synchronously when flag is provided', function (done) {
|
it('should add a request interceptor that is executed synchronously when flag is provided', function (done) {
|
||||||
var asyncFlag = false;
|
let asyncFlag = false;
|
||||||
axios.interceptors.request.use(function (config) {
|
axios.interceptors.request.use(function (config) {
|
||||||
config.headers.test = 'added by synchronous interceptor';
|
config.headers.test = 'added by synchronous interceptor';
|
||||||
expect(asyncFlag).toBe(false);
|
expect(asyncFlag).toBe(false);
|
||||||
@@ -61,7 +61,7 @@ describe('interceptors', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should execute asynchronously when not all interceptors are explicitly flagged as synchronous', function (done) {
|
it('should execute asynchronously when not all interceptors are explicitly flagged as synchronous', function (done) {
|
||||||
var asyncFlag = false;
|
let asyncFlag = false;
|
||||||
axios.interceptors.request.use(function (config) {
|
axios.interceptors.request.use(function (config) {
|
||||||
config.headers.foo = 'uh oh, async';
|
config.headers.foo = 'uh oh, async';
|
||||||
expect(asyncFlag).toBe(true);
|
expect(asyncFlag).toBe(true);
|
||||||
@@ -126,7 +126,7 @@ describe('interceptors', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('does not run async interceptor if runWhen function is provided and resolves to false (and run synchronously)', function (done) {
|
it('does not run async interceptor if runWhen function is provided and resolves to false (and run synchronously)', function (done) {
|
||||||
var asyncFlag = false;
|
let asyncFlag = false;
|
||||||
|
|
||||||
function onPostCall(config) {
|
function onPostCall(config) {
|
||||||
return config.method === 'post';
|
return config.method === 'post';
|
||||||
@@ -153,13 +153,13 @@ describe('interceptors', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should add a request interceptor with an onRejected block that is called if interceptor code fails', function (done) {
|
it('should add a request interceptor with an onRejected block that is called if interceptor code fails', function (done) {
|
||||||
var rejectedSpy = jasmine.createSpy('rejectedSpy');
|
const rejectedSpy = jasmine.createSpy('rejectedSpy');
|
||||||
var error = new Error('deadly error');
|
const error = new Error('deadly error');
|
||||||
axios.interceptors.request.use(function () {
|
axios.interceptors.request.use(function () {
|
||||||
throw error;
|
throw error;
|
||||||
}, rejectedSpy, { synchronous: true });
|
}, rejectedSpy, { synchronous: true });
|
||||||
|
|
||||||
axios('/foo');
|
axios('/foo').catch(done);
|
||||||
|
|
||||||
getAjaxRequest().then(function () {
|
getAjaxRequest().then(function () {
|
||||||
expect(rejectedSpy).toHaveBeenCalledWith(error);
|
expect(rejectedSpy).toHaveBeenCalledWith(error);
|
||||||
@@ -228,7 +228,7 @@ describe('interceptors', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should add a response interceptor', function (done) {
|
it('should add a response interceptor', function (done) {
|
||||||
var response;
|
let response;
|
||||||
|
|
||||||
axios.interceptors.response.use(function (data) {
|
axios.interceptors.response.use(function (data) {
|
||||||
data.data = data.data + ' - modified by interceptor';
|
data.data = data.data + ' - modified by interceptor';
|
||||||
@@ -253,7 +253,7 @@ describe('interceptors', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should add a response interceptor when request interceptor is defined', function (done) {
|
it('should add a response interceptor when request interceptor is defined', function (done) {
|
||||||
var response;
|
let response;
|
||||||
|
|
||||||
axios.interceptors.request.use(function (data) {
|
axios.interceptors.request.use(function (data) {
|
||||||
return data;
|
return data;
|
||||||
@@ -282,7 +282,7 @@ describe('interceptors', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should add a response interceptor that returns a new data object', function (done) {
|
it('should add a response interceptor that returns a new data object', function (done) {
|
||||||
var response;
|
let response;
|
||||||
|
|
||||||
axios.interceptors.response.use(function () {
|
axios.interceptors.response.use(function () {
|
||||||
return {
|
return {
|
||||||
@@ -308,7 +308,7 @@ describe('interceptors', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should add a response interceptor that returns a promise', function (done) {
|
it('should add a response interceptor that returns a promise', function (done) {
|
||||||
var response;
|
let response;
|
||||||
|
|
||||||
axios.interceptors.response.use(function (data) {
|
axios.interceptors.response.use(function (data) {
|
||||||
return new Promise(function (resolve) {
|
return new Promise(function (resolve) {
|
||||||
@@ -342,7 +342,7 @@ describe('interceptors', function () {
|
|||||||
describe('and when the response was fulfilled', function () {
|
describe('and when the response was fulfilled', function () {
|
||||||
|
|
||||||
function fireRequestAndExpect(expectation) {
|
function fireRequestAndExpect(expectation) {
|
||||||
var response;
|
let response;
|
||||||
axios('/foo').then(function(data) {
|
axios('/foo').then(function(data) {
|
||||||
response = data;
|
response = data;
|
||||||
});
|
});
|
||||||
@@ -359,8 +359,8 @@ describe('interceptors', function () {
|
|||||||
}
|
}
|
||||||
|
|
||||||
it('then each interceptor is executed', function (done) {
|
it('then each interceptor is executed', function (done) {
|
||||||
var interceptor1 = jasmine.createSpy('interceptor1');
|
const interceptor1 = jasmine.createSpy('interceptor1');
|
||||||
var interceptor2 = jasmine.createSpy('interceptor2');
|
const interceptor2 = jasmine.createSpy('interceptor2');
|
||||||
axios.interceptors.response.use(interceptor1);
|
axios.interceptors.response.use(interceptor1);
|
||||||
axios.interceptors.response.use(interceptor2);
|
axios.interceptors.response.use(interceptor2);
|
||||||
|
|
||||||
@@ -372,8 +372,8 @@ describe('interceptors', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('then they are executed in the order they were added', function (done) {
|
it('then they are executed in the order they were added', function (done) {
|
||||||
var interceptor1 = jasmine.createSpy('interceptor1');
|
const interceptor1 = jasmine.createSpy('interceptor1');
|
||||||
var interceptor2 = jasmine.createSpy('interceptor2');
|
const interceptor2 = jasmine.createSpy('interceptor2');
|
||||||
axios.interceptors.response.use(interceptor1);
|
axios.interceptors.response.use(interceptor1);
|
||||||
axios.interceptors.response.use(interceptor2);
|
axios.interceptors.response.use(interceptor2);
|
||||||
|
|
||||||
@@ -433,7 +433,7 @@ describe('interceptors', function () {
|
|||||||
axios.interceptors.response.use(function() {
|
axios.interceptors.response.use(function() {
|
||||||
throw Error('throwing interceptor');
|
throw Error('throwing interceptor');
|
||||||
});
|
});
|
||||||
var interceptor2 = jasmine.createSpy('interceptor2');
|
const interceptor2 = jasmine.createSpy('interceptor2');
|
||||||
axios.interceptors.response.use(interceptor2);
|
axios.interceptors.response.use(interceptor2);
|
||||||
|
|
||||||
fireRequestCatchAndExpect(function () {
|
fireRequestCatchAndExpect(function () {
|
||||||
@@ -446,8 +446,8 @@ describe('interceptors', function () {
|
|||||||
axios.interceptors.response.use(function() {
|
axios.interceptors.response.use(function() {
|
||||||
throw Error('throwing interceptor');
|
throw Error('throwing interceptor');
|
||||||
});
|
});
|
||||||
var unusedFulfillInterceptor = function() {};
|
const unusedFulfillInterceptor = function() {};
|
||||||
var rejectIntercept = jasmine.createSpy('rejectIntercept');
|
const rejectIntercept = jasmine.createSpy('rejectIntercept');
|
||||||
axios.interceptors.response.use(unusedFulfillInterceptor, rejectIntercept);
|
axios.interceptors.response.use(unusedFulfillInterceptor, rejectIntercept);
|
||||||
|
|
||||||
fireRequestCatchAndExpect(function () {
|
fireRequestCatchAndExpect(function () {
|
||||||
@@ -455,17 +455,17 @@ describe('interceptors', function () {
|
|||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('once caught, another following fulfill-interceptor is called again (just like in a promise chain)', function (done) {
|
it('once caught, another following fulfill-interceptor is called again (just like in a promise chain)', function (done) {
|
||||||
axios.interceptors.response.use(function() {
|
axios.interceptors.response.use(function() {
|
||||||
throw Error('throwing interceptor');
|
throw Error('throwing interceptor');
|
||||||
});
|
});
|
||||||
|
|
||||||
var unusedFulfillInterceptor = function() {};
|
const unusedFulfillInterceptor = function() {};
|
||||||
var catchingThrowingInterceptor = function() {};
|
const catchingThrowingInterceptor = function() {};
|
||||||
axios.interceptors.response.use(unusedFulfillInterceptor, catchingThrowingInterceptor);
|
axios.interceptors.response.use(unusedFulfillInterceptor, catchingThrowingInterceptor);
|
||||||
|
|
||||||
var interceptor3 = jasmine.createSpy('interceptor3');
|
const interceptor3 = jasmine.createSpy('interceptor3');
|
||||||
axios.interceptors.response.use(interceptor3);
|
axios.interceptors.response.use(interceptor3);
|
||||||
|
|
||||||
fireRequestCatchAndExpect(function () {
|
fireRequestCatchAndExpect(function () {
|
||||||
@@ -478,7 +478,7 @@ describe('interceptors', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should allow removing interceptors', function (done) {
|
it('should allow removing interceptors', function (done) {
|
||||||
var response, intercept;
|
let response, intercept;
|
||||||
|
|
||||||
axios.interceptors.response.use(function (data) {
|
axios.interceptors.response.use(function (data) {
|
||||||
data.data = data.data + '1';
|
data.data = data.data + '1';
|
||||||
@@ -513,13 +513,13 @@ describe('interceptors', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should remove async interceptor before making request and execute synchronously', function (done) {
|
it('should remove async interceptor before making request and execute synchronously', function (done) {
|
||||||
var asyncFlag = false;
|
let asyncFlag = false;
|
||||||
var asyncIntercept = axios.interceptors.request.use(function (config) {
|
const asyncIntercept = axios.interceptors.request.use(function (config) {
|
||||||
config.headers.async = 'async it!';
|
config.headers.async = 'async it!';
|
||||||
return config;
|
return config;
|
||||||
}, null, { synchronous: false });
|
}, null, { synchronous: false });
|
||||||
|
|
||||||
var syncIntercept = axios.interceptors.request.use(function (config) {
|
const syncIntercept = axios.interceptors.request.use(function (config) {
|
||||||
config.headers.sync = 'hello world';
|
config.headers.sync = 'hello world';
|
||||||
expect(asyncFlag).toBe(false);
|
expect(asyncFlag).toBe(false);
|
||||||
return config;
|
return config;
|
||||||
@@ -555,7 +555,7 @@ describe('interceptors', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should modify base URL in request interceptor', function (done) {
|
it('should modify base URL in request interceptor', function (done) {
|
||||||
var instance = axios.create({
|
const instance = axios.create({
|
||||||
baseURL: 'http://test.com/'
|
baseURL: 'http://test.com/'
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -573,7 +573,7 @@ describe('interceptors', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should clear all request interceptors', function () {
|
it('should clear all request interceptors', function () {
|
||||||
var instance = axios.create({
|
const instance = axios.create({
|
||||||
baseURL: 'http://test.com/'
|
baseURL: 'http://test.com/'
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -587,7 +587,7 @@ describe('interceptors', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should clear all response interceptors', function () {
|
it('should clear all response interceptors', function () {
|
||||||
var instance = axios.create({
|
const instance = axios.create({
|
||||||
baseURL: 'http://test.com/'
|
baseURL: 'http://test.com/'
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user