docs: 初始化示例项目
parent
74856f7fde
commit
359b09172e
|
@ -1,4 +1,5 @@
|
|||
{
|
||||
"root": true,
|
||||
"env": {
|
||||
"es2022": true,
|
||||
"node": true
|
||||
|
@ -6,10 +7,10 @@
|
|||
"extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended"],
|
||||
"parser": "@typescript-eslint/parser",
|
||||
"plugins": ["@typescript-eslint"],
|
||||
"root": true,
|
||||
"rules": {
|
||||
"@typescript-eslint/no-explicit-any": 0,
|
||||
"@typescript-eslint/no-non-null-assertion": 0,
|
||||
"@typescript-eslint/ban-ts-comment": 0
|
||||
"@typescript-eslint/ban-ts-comment": 0,
|
||||
"no-mixed-spaces-and-tabs": 0
|
||||
}
|
||||
}
|
||||
|
|
|
@ -44,7 +44,7 @@ jobs:
|
|||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
tag_name: ${{ github.ref }}
|
||||
name: Release ${{ github.ref }}
|
||||
name: Release ${{ github.ref_name }}
|
||||
prerelease: ${{ steps.prerelease.outputs.result }}
|
||||
body_path: 'RELEASELOG.md'
|
||||
files: 'dist/**.zip'
|
||||
|
|
|
@ -1 +1,2 @@
|
|||
CHANGELOG.md
|
||||
dist/
|
||||
|
|
|
@ -1,11 +1,10 @@
|
|||
{
|
||||
"printWidth": 80,
|
||||
"tabWidth": 2,
|
||||
"useTabs": true,
|
||||
"semi": false,
|
||||
"useTabs": false,
|
||||
"semi": true,
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all",
|
||||
"bracketSpacing": true,
|
||||
"arrowParens": "always",
|
||||
"jsxSingleQuote": true
|
||||
"arrowParens": "always"
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
{
|
||||
"presets": [
|
||||
[
|
||||
"taro",
|
||||
{
|
||||
"framework": "vue3",
|
||||
"ts": true
|
||||
}
|
||||
]
|
||||
]
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
{
|
||||
"extends": ["plugin:vue/vue3-essential"],
|
||||
"parser": "vue-eslint-parser",
|
||||
"parserOptions": {
|
||||
"parser": "@typescript-eslint/parser",
|
||||
"sourceType": "module"
|
||||
},
|
||||
"rules": {
|
||||
"vue/multi-word-component-names": "off"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
dist/
|
||||
deploy_versions/
|
||||
.temp/
|
||||
.rn_temp/
|
||||
node_modules/
|
||||
.DS_Store
|
||||
.swc
|
||||
config/**.js
|
|
@ -0,0 +1,2 @@
|
|||
dist/
|
||||
config/**.js
|
|
@ -0,0 +1,8 @@
|
|||
export default {
|
||||
env: {
|
||||
NODE_ENV: '"development"',
|
||||
},
|
||||
defineConstants: {},
|
||||
mini: {},
|
||||
h5: {},
|
||||
};
|
|
@ -0,0 +1,79 @@
|
|||
import dev from './dev';
|
||||
import prod from './prod';
|
||||
|
||||
export default (merge) => {
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
return merge({}, config, dev);
|
||||
}
|
||||
return merge({}, config, prod);
|
||||
};
|
||||
|
||||
const config = {
|
||||
projectName: 'axios-miniprogram',
|
||||
date: '2023-5-5',
|
||||
designWidth: 750,
|
||||
deviceRatio: {
|
||||
640: 2.34 / 2,
|
||||
750: 1,
|
||||
828: 1.81 / 2,
|
||||
},
|
||||
sourceRoot: 'src',
|
||||
outputRoot: 'dist',
|
||||
plugins: [],
|
||||
defineConstants: {},
|
||||
copy: {
|
||||
patterns: [],
|
||||
options: {},
|
||||
},
|
||||
framework: 'vue3',
|
||||
compiler: 'webpack5',
|
||||
cache: {
|
||||
enable: false, // Webpack 持久化缓存配置,建议开启。默认配置请参考:https://docs.taro.zone/docs/config-detail#cache
|
||||
},
|
||||
mini: {
|
||||
postcss: {
|
||||
pxtransform: {
|
||||
enable: true,
|
||||
config: {},
|
||||
},
|
||||
url: {
|
||||
enable: true,
|
||||
config: {
|
||||
limit: 1024, // 设定转换尺寸上限
|
||||
},
|
||||
},
|
||||
cssModules: {
|
||||
enable: false, // 默认为 false,如需使用 css modules 功能,则设为 true
|
||||
config: {
|
||||
namingPattern: 'module', // 转换模式,取值为 global/module
|
||||
generateScopedName: '[name]__[local]___[hash:base64:5]',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
h5: {
|
||||
publicPath: '/',
|
||||
staticDirectory: 'static',
|
||||
postcss: {
|
||||
autoprefixer: {
|
||||
enable: true,
|
||||
config: {},
|
||||
},
|
||||
cssModules: {
|
||||
enable: false, // 默认为 false,如需使用 css modules 功能,则设为 true
|
||||
config: {
|
||||
namingPattern: 'module', // 转换模式,取值为 global/module
|
||||
generateScopedName: '[name]__[local]___[hash:base64:5]',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
rn: {
|
||||
appName: 'taroDemo',
|
||||
postcss: {
|
||||
cssModules: {
|
||||
enable: false, // 默认为 false,如需使用 css modules 功能,则设为 true
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
|
@ -0,0 +1,35 @@
|
|||
export default {
|
||||
env: {
|
||||
NODE_ENV: '"production"',
|
||||
},
|
||||
defineConstants: {},
|
||||
mini: {},
|
||||
h5: {
|
||||
/**
|
||||
* WebpackChain 插件配置
|
||||
* @docs https://github.com/neutrinojs/webpack-chain
|
||||
*/
|
||||
// webpackChain (chain) {
|
||||
// /**
|
||||
// * 如果 h5 端编译后体积过大,可以使用 webpack-bundle-analyzer 插件对打包体积进行分析。
|
||||
// * @docs https://github.com/webpack-contrib/webpack-bundle-analyzer
|
||||
// */
|
||||
// chain.plugin('analyzer')
|
||||
// .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin, [])
|
||||
// /**
|
||||
// * 如果 h5 端首屏加载时间过长,可以使用 prerender-spa-plugin 插件预加载首页。
|
||||
// * @docs https://github.com/chrisvfritz/prerender-spa-plugin
|
||||
// */
|
||||
// const path = require('path')
|
||||
// const Prerender = require('prerender-spa-plugin')
|
||||
// const staticDir = path.join(__dirname, '..', 'dist')
|
||||
// chain
|
||||
// .plugin('prerender')
|
||||
// .use(new Prerender({
|
||||
// staticDir,
|
||||
// routes: [ '/pages/index/index' ],
|
||||
// postProcess: (context) => ({ ...context, outputPath: path.join(staticDir, 'index.html') })
|
||||
// }))
|
||||
// }
|
||||
},
|
||||
};
|
|
@ -0,0 +1,31 @@
|
|||
/// <reference types="@tarojs/taro" />
|
||||
|
||||
declare module '*.png';
|
||||
declare module '*.gif';
|
||||
declare module '*.jpg';
|
||||
declare module '*.jpeg';
|
||||
declare module '*.svg';
|
||||
declare module '*.css';
|
||||
declare module '*.less';
|
||||
declare module '*.scss';
|
||||
declare module '*.sass';
|
||||
declare module '*.styl';
|
||||
|
||||
declare namespace NodeJS {
|
||||
interface ProcessEnv {
|
||||
TARO_ENV:
|
||||
| 'weapp'
|
||||
| 'swan'
|
||||
| 'alipay'
|
||||
| 'h5'
|
||||
| 'rn'
|
||||
| 'tt'
|
||||
| 'quickapp'
|
||||
| 'qq'
|
||||
| 'jd';
|
||||
}
|
||||
}
|
||||
|
||||
declare module '@tarojs/components' {
|
||||
export * from '@tarojs/components/types/index.vue3';
|
||||
}
|
|
@ -0,0 +1,58 @@
|
|||
{
|
||||
"name": "example",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build:weapp": "taro build --type weapp",
|
||||
"build:swan": "taro build --type swan",
|
||||
"build:alipay": "taro build --type alipay",
|
||||
"build:tt": "taro build --type tt",
|
||||
"build:h5": "taro build --type h5",
|
||||
"build:rn": "taro build --type rn",
|
||||
"build:qq": "taro build --type qq",
|
||||
"build:jd": "taro build --type jd",
|
||||
"build:quickapp": "taro build --type quickapp",
|
||||
"dev:weapp": "npm run build:weapp -- --watch",
|
||||
"dev:swan": "npm run build:swan -- --watch",
|
||||
"dev:alipay": "npm run build:alipay -- --watch",
|
||||
"dev:tt": "npm run build:tt -- --watch",
|
||||
"dev:h5": "npm run build:h5 -- --watch",
|
||||
"dev:rn": "npm run build:rn -- --watch",
|
||||
"dev:qq": "npm run build:qq -- --watch",
|
||||
"dev:jd": "npm run build:jd -- --watch",
|
||||
"dev:quickapp": "npm run build:quickapp -- --watch"
|
||||
},
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.7.7",
|
||||
"@tarojs/components": "3.6.6",
|
||||
"@tarojs/helper": "3.6.6",
|
||||
"@tarojs/plugin-framework-vue3": "3.6.6",
|
||||
"@tarojs/plugin-platform-alipay": "3.6.6",
|
||||
"@tarojs/plugin-platform-h5": "3.6.6",
|
||||
"@tarojs/plugin-platform-jd": "3.6.6",
|
||||
"@tarojs/plugin-platform-qq": "3.6.6",
|
||||
"@tarojs/plugin-platform-swan": "3.6.6",
|
||||
"@tarojs/plugin-platform-tt": "3.6.6",
|
||||
"@tarojs/plugin-platform-weapp": "3.6.6",
|
||||
"@tarojs/runtime": "3.6.6",
|
||||
"@tarojs/shared": "3.6.6",
|
||||
"@tarojs/taro": "3.6.6",
|
||||
"vue": "^3.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.8.0",
|
||||
"@tarojs/cli": "3.6.6",
|
||||
"@tarojs/webpack5-runner": "3.6.6",
|
||||
"@types/webpack-env": "^1.13.6",
|
||||
"@vue/babel-plugin-jsx": "^1.0.6",
|
||||
"@vue/compiler-sfc": "^3.0.0",
|
||||
"babel-preset-taro": "3.6.6",
|
||||
"css-loader": "3.4.2",
|
||||
"eslint-plugin-vue": "^8.0.0",
|
||||
"postcss": "^8.4.18",
|
||||
"style-loader": "1.3.0",
|
||||
"stylelint": "^14.4.0",
|
||||
"vue-eslint-parser": "^9.2.0",
|
||||
"vue-loader": "^17.0.0",
|
||||
"webpack": "5.78.0"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
{
|
||||
"miniprogramRoot": "./dist",
|
||||
"projectname": "axios-miniprogram",
|
||||
"appid": "wx48e277051b32f95b",
|
||||
"setting": {
|
||||
"urlCheck": true,
|
||||
"es6": false,
|
||||
"enhance": false,
|
||||
"compileHotReLoad": false,
|
||||
"postcss": false,
|
||||
"minified": false
|
||||
},
|
||||
"compileType": "miniprogram"
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
{
|
||||
"miniprogramRoot": "./",
|
||||
"projectname": "axios-miniprogram",
|
||||
"appid": "testAppId",
|
||||
"setting": {
|
||||
"es6": false,
|
||||
"minified": false
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
export default defineAppConfig({
|
||||
pages: ['pages/index/index'],
|
||||
window: {
|
||||
backgroundTextStyle: 'light',
|
||||
navigationBarBackgroundColor: '#fff',
|
||||
navigationBarTitleText: 'axios-miniprogram',
|
||||
navigationBarTextStyle: 'black',
|
||||
},
|
||||
});
|
|
@ -0,0 +1,4 @@
|
|||
import { createApp } from 'vue';
|
||||
import './app.css';
|
||||
|
||||
export default createApp({});
|
|
@ -0,0 +1,17 @@
|
|||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
|
||||
<meta content="width=device-width,initial-scale=1,user-scalable=no" name="viewport">
|
||||
<meta name="apple-mobile-web-app-capable" content="yes">
|
||||
<meta name="apple-touch-fullscreen" content="yes">
|
||||
<meta name="format-detection" content="telephone=no,address=no">
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="white">
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" >
|
||||
<title>example</title>
|
||||
<script><%= htmlWebpackPlugin.options.script %></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,3 @@
|
|||
export default definePageConfig({
|
||||
navigationBarTitleText: '首页',
|
||||
});
|
|
@ -0,0 +1,16 @@
|
|||
<template>
|
||||
<view class="index">
|
||||
<text>{{ msg }}</text>
|
||||
</view>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { ref } from 'vue'
|
||||
import './index.css'
|
||||
|
||||
const msg = ref('Hello world')
|
||||
|
||||
defineExpose({
|
||||
msg,
|
||||
})
|
||||
</script>
|
|
@ -0,0 +1,18 @@
|
|||
{
|
||||
"extends": ["../tsconfig.json"],
|
||||
"compilerOptions": {
|
||||
"removeComments": false,
|
||||
"preserveConstEnums": true,
|
||||
"experimentalDecorators": true,
|
||||
"noImplicitAny": false,
|
||||
"outDir": "lib",
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"strictNullChecks": true,
|
||||
"sourceMap": true,
|
||||
"jsx": "preserve",
|
||||
"allowJs": true,
|
||||
"resolveJsonModule": true
|
||||
},
|
||||
"include": ["./src", "global.d.ts"]
|
||||
}
|
|
@ -47,7 +47,8 @@
|
|||
"docs:build": "pnpm -C docs build",
|
||||
"docs:preview": "pnpm -C docs preview",
|
||||
"docs:deploy": "esno scripts/docs.deploy.ts",
|
||||
"start": "esno scripts/start.ts"
|
||||
"start": "esno scripts/start.ts",
|
||||
"tidy": "prettier **/*.{js,json} --write && prettier **/*.ts?(x) --parser=typescript --write"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@commitlint/cli": "^17.4.4",
|
||||
|
@ -90,7 +91,7 @@
|
|||
}
|
||||
},
|
||||
"lint-staged": {
|
||||
"*.{mjs,json}": [
|
||||
"*.{js,json}": [
|
||||
"prettier --write"
|
||||
],
|
||||
"*.ts?(x)": [
|
||||
|
@ -103,7 +104,8 @@
|
|||
"ignoreMissing": [
|
||||
"@algolia/client-search",
|
||||
"esbuild",
|
||||
"vite"
|
||||
"vite",
|
||||
"eslint"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
|
7716
pnpm-lock.yaml
7716
pnpm-lock.yaml
File diff suppressed because it is too large
Load Diff
|
@ -1,2 +1,3 @@
|
|||
packages:
|
||||
- docs
|
||||
- example
|
||||
|
|
|
@ -1,34 +1,34 @@
|
|||
import minimist from 'minimist'
|
||||
import consola from 'consola'
|
||||
import minimist from 'minimist';
|
||||
import consola from 'consola';
|
||||
|
||||
import { distPath, exec } from './utils'
|
||||
import { checkSize } from './checkSize'
|
||||
import { safeExit } from './utils'
|
||||
import { distPath, exec } from './utils';
|
||||
import { checkSize } from './checkSize';
|
||||
import { safeExit } from './utils';
|
||||
|
||||
const args = minimist(process.argv.slice(2))
|
||||
const watch = Boolean(args.watch || args.w)
|
||||
const all = Boolean(args.all || args.a)
|
||||
const sourceMap = all || Boolean(args.sourceMap || args.s)
|
||||
const dts = all || Boolean(args.dts || args.d)
|
||||
const args = minimist(process.argv.slice(2));
|
||||
const watch = Boolean(args.watch || args.w);
|
||||
const all = Boolean(args.all || args.a);
|
||||
const sourceMap = all || Boolean(args.sourceMap || args.s);
|
||||
const dts = all || Boolean(args.dts || args.d);
|
||||
|
||||
main()
|
||||
main();
|
||||
|
||||
function main() {
|
||||
exec('rimraf dist')
|
||||
exec('rimraf dist');
|
||||
|
||||
consola.info('Rollup')
|
||||
consola.info('Rollup');
|
||||
|
||||
safeExit(() => {
|
||||
exec(
|
||||
`rollup -c rollup.config.ts --configPlugin typescript ${
|
||||
watch ? '-w' : ''
|
||||
} --environment SOURCE_MAP:${sourceMap},DTS:${dts}`,
|
||||
)
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
if (!watch) {
|
||||
checkSize(`${distPath}/**.js`)
|
||||
checkSize(`${distPath}/**.js`);
|
||||
}
|
||||
|
||||
console.info('\n')
|
||||
console.info('\n');
|
||||
}
|
||||
|
|
|
@ -1,8 +1,27 @@
|
|||
import enquirer from 'enquirer'
|
||||
import { exec } from './utils'
|
||||
import { safeExit } from './utils'
|
||||
import enquirer from 'enquirer';
|
||||
import { exec, resolve } from './utils';
|
||||
import { safeExit } from './utils';
|
||||
|
||||
const metas = [
|
||||
const configPath = resolve('example/config');
|
||||
const configTempPath = resolve('example/config/temp');
|
||||
|
||||
safeExit(main);
|
||||
|
||||
async function main() {
|
||||
const { platform } = await enquirer.prompt<{ platform: string }>({
|
||||
type: 'select',
|
||||
name: 'platform',
|
||||
message: '请选择启动平台',
|
||||
choices: metas(),
|
||||
});
|
||||
|
||||
exec(`tsc ${configTempPath}/**.ts --outDir ${configPath}`);
|
||||
|
||||
exec(`pnpm -C example dev:${platform}`);
|
||||
}
|
||||
|
||||
function metas() {
|
||||
return [
|
||||
{ name: 'weapp', message: '微信小程序' },
|
||||
{ name: 'swan', message: '百度小程序' },
|
||||
{ name: 'alipay', message: '支付宝小程序' },
|
||||
|
@ -13,17 +32,5 @@ const metas = [
|
|||
{ name: 'lark', message: '飞书小程序' },
|
||||
{ name: 'kwai', message: '快手小程序' },
|
||||
{ name: 'h5', message: 'H5' },
|
||||
]
|
||||
|
||||
safeExit(main)
|
||||
|
||||
async function main() {
|
||||
const { platform } = await enquirer.prompt<{ platform: string }>({
|
||||
type: 'select',
|
||||
name: 'platform',
|
||||
message: '请选择启动平台',
|
||||
choices: metas,
|
||||
})
|
||||
|
||||
exec(`pnpm -C example dev:${platform}`)
|
||||
];
|
||||
}
|
||||
|
|
|
@ -1,39 +1,40 @@
|
|||
import { isPromise } from 'node:util/types'
|
||||
import path from 'node:path'
|
||||
import { createRequire } from 'node:module'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { ExecSyncOptions, execSync } from 'node:child_process'
|
||||
import consola from 'consola'
|
||||
import { isPromise } from 'node:util/types';
|
||||
import path from 'node:path';
|
||||
import { createRequire } from 'node:module';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { ExecSyncOptions, execSync } from 'node:child_process';
|
||||
import consola from 'consola';
|
||||
|
||||
export const __dirname = fileURLToPath(new URL('../', import.meta.url))
|
||||
export const require = createRequire(import.meta.url)
|
||||
export const pkgPath = path.resolve(__dirname, 'package.json')
|
||||
export const distPath = path.resolve(__dirname, 'dist')
|
||||
export const __dirname = fileURLToPath(new URL('../', import.meta.url));
|
||||
export const require = createRequire(import.meta.url);
|
||||
export const pkgPath = path.resolve(__dirname, 'package.json');
|
||||
export const distPath = path.resolve(__dirname, 'dist');
|
||||
|
||||
export const resolve = (...paths: string[]) => path.resolve(__dirname, ...paths)
|
||||
export const resolve = (...paths: string[]) =>
|
||||
path.resolve(__dirname, ...paths);
|
||||
|
||||
export const exec = (command: string, options: ExecSyncOptions = {}) =>
|
||||
execSync(command, {
|
||||
stdio: 'inherit',
|
||||
encoding: 'utf-8',
|
||||
...options,
|
||||
})
|
||||
});
|
||||
|
||||
export const getPkgJSON = () => require(pkgPath)
|
||||
export const getPkgJSON = () => require(pkgPath);
|
||||
|
||||
export function safeExit(run: () => unknown) {
|
||||
try {
|
||||
const p = run()
|
||||
const p = run();
|
||||
|
||||
if (isPromise(p)) {
|
||||
return p.catch(exit)
|
||||
return p.catch(exit);
|
||||
}
|
||||
} catch {
|
||||
exit()
|
||||
exit();
|
||||
}
|
||||
}
|
||||
|
||||
function exit() {
|
||||
consola.error('已退出')
|
||||
process.exit()
|
||||
consola.error('已退出');
|
||||
process.exit();
|
||||
}
|
||||
|
|
|
@ -2,28 +2,28 @@ import {
|
|||
PLAIN_METHODS,
|
||||
WITH_DATA_METHODS,
|
||||
WITH_PARAMS_METHODS,
|
||||
} from '../constants/methods'
|
||||
import { isString } from '../helpers/isTypes'
|
||||
import { dispatchRequest } from '../request/dispatchRequest'
|
||||
import { CancelToken } from '../request/cancel'
|
||||
import { AxiosTransformer } from '../request/transformData'
|
||||
import { deepMerge } from '../helpers/deepMerge'
|
||||
} from '../constants/methods';
|
||||
import { isString } from '../helpers/isTypes';
|
||||
import { dispatchRequest } from '../request/dispatchRequest';
|
||||
import { CancelToken } from '../request/cancel';
|
||||
import { AxiosTransformer } from '../request/transformData';
|
||||
import { deepMerge } from '../helpers/deepMerge';
|
||||
import {
|
||||
AxiosAdapter,
|
||||
AxiosAdapterRequestMethod,
|
||||
AxiosAdapterPlatformTask,
|
||||
AxiosAdapterRequestConfig,
|
||||
AxiosAdapterResponseData,
|
||||
} from '../adpater/createAdapter'
|
||||
} from '../adpater/createAdapter';
|
||||
import InterceptorManager, {
|
||||
Interceptor,
|
||||
InterceptorExecutor,
|
||||
} from './InterceptorManager'
|
||||
} from './InterceptorManager';
|
||||
import MiddlewareManager, {
|
||||
MiddlewareCallback,
|
||||
MiddlewareContext,
|
||||
} from './MiddlewareManager'
|
||||
import { mergeConfig } from './mergeConfig'
|
||||
} from './MiddlewareManager';
|
||||
import { mergeConfig } from './mergeConfig';
|
||||
|
||||
/**
|
||||
* 请求方法
|
||||
|
@ -38,7 +38,7 @@ export type AxiosRequestMethod =
|
|||
| 'patch'
|
||||
| 'delete'
|
||||
| 'trace'
|
||||
| 'connect'
|
||||
| 'connect';
|
||||
|
||||
/**
|
||||
* 请求头
|
||||
|
@ -47,39 +47,39 @@ export interface AxiosRequestHeaders extends AnyObject {
|
|||
/**
|
||||
* 通用请求头
|
||||
*/
|
||||
common?: AnyObject
|
||||
common?: AnyObject;
|
||||
/**
|
||||
* options 请求头
|
||||
*/
|
||||
options?: AnyObject
|
||||
options?: AnyObject;
|
||||
/**
|
||||
* get 请求头
|
||||
*/
|
||||
get?: AnyObject
|
||||
get?: AnyObject;
|
||||
/**
|
||||
* head 请求头
|
||||
*/
|
||||
head?: AnyObject
|
||||
head?: AnyObject;
|
||||
/**
|
||||
* post 请求头
|
||||
*/
|
||||
post?: AnyObject
|
||||
post?: AnyObject;
|
||||
/**
|
||||
* put 请求头
|
||||
*/
|
||||
put?: AnyObject
|
||||
put?: AnyObject;
|
||||
/**
|
||||
* delete 请求头
|
||||
*/
|
||||
delete?: AnyObject
|
||||
delete?: AnyObject;
|
||||
/**
|
||||
* trace 请求头
|
||||
*/
|
||||
trace?: AnyObject
|
||||
trace?: AnyObject;
|
||||
/**
|
||||
* connect 请求头
|
||||
*/
|
||||
connect?: AnyObject
|
||||
connect?: AnyObject;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -89,11 +89,11 @@ export interface AxiosRequestFormData extends AnyObject {
|
|||
/**
|
||||
* 文件名
|
||||
*/
|
||||
name: string
|
||||
name: string;
|
||||
/**
|
||||
* 文件路径
|
||||
*/
|
||||
filePath: string
|
||||
filePath: string;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -103,12 +103,12 @@ export type AxiosRequestData =
|
|||
| string
|
||||
| AnyObject
|
||||
| ArrayBuffer
|
||||
| AxiosRequestFormData
|
||||
| AxiosRequestFormData;
|
||||
|
||||
/**
|
||||
* 响应数据
|
||||
*/
|
||||
export type AxiosResponseData = number | AxiosAdapterResponseData
|
||||
export type AxiosResponseData = number | AxiosAdapterResponseData;
|
||||
|
||||
/**
|
||||
* 进度对象
|
||||
|
@ -117,7 +117,7 @@ export interface AxiosProgressEvent extends AnyObject {
|
|||
/**
|
||||
* 上传进度百分比
|
||||
*/
|
||||
progress: number
|
||||
progress: number;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -127,18 +127,18 @@ export interface AxiosDownloadProgressEvent extends AxiosProgressEvent {
|
|||
/**
|
||||
* 已经下载的数据长度,单位 Bytes
|
||||
*/
|
||||
totalBytesWritten: number
|
||||
totalBytesWritten: number;
|
||||
/**
|
||||
* 预预期需要下载的数据总长度,单位 Bytes
|
||||
*/
|
||||
totalBytesExpectedToWrite: number
|
||||
totalBytesExpectedToWrite: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 监听下载进度
|
||||
*/
|
||||
export interface AxiosDownloadProgressCallback {
|
||||
(event: AxiosDownloadProgressEvent): void
|
||||
(event: AxiosDownloadProgressEvent): void;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -148,18 +148,18 @@ export interface AxiosUploadProgressEvent extends AxiosProgressEvent {
|
|||
/**
|
||||
* 已经上传的数据长度,单位 Bytes
|
||||
*/
|
||||
totalBytesSent: number
|
||||
totalBytesSent: number;
|
||||
/**
|
||||
* 预期需要上传的数据总长度,单位 Bytes
|
||||
*/
|
||||
totalBytesExpectedToSend: number
|
||||
totalBytesExpectedToSend: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 监听上传进度
|
||||
*/
|
||||
export interface AxiosUploadProgressCallback {
|
||||
(event: AxiosUploadProgressEvent): void
|
||||
(event: AxiosUploadProgressEvent): void;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -172,71 +172,71 @@ export interface AxiosRequestConfig
|
|||
/**
|
||||
* 请求适配器
|
||||
*/
|
||||
adapter?: AxiosAdapter
|
||||
adapter?: AxiosAdapter;
|
||||
/**
|
||||
* 基础路径
|
||||
*/
|
||||
baseURL?: string
|
||||
baseURL?: string;
|
||||
/**
|
||||
* 请求的 URL
|
||||
*/
|
||||
url?: string
|
||||
url?: string;
|
||||
/**
|
||||
* 请求参数
|
||||
*/
|
||||
params?: AnyObject
|
||||
params?: AnyObject;
|
||||
/**
|
||||
* 请求数据
|
||||
*/
|
||||
data?: AxiosRequestData
|
||||
data?: AxiosRequestData;
|
||||
/**
|
||||
* 请求头
|
||||
*/
|
||||
headers?: AxiosRequestHeaders
|
||||
headers?: AxiosRequestHeaders;
|
||||
/**
|
||||
* 请求方法
|
||||
*/
|
||||
method?: AxiosRequestMethod
|
||||
method?: AxiosRequestMethod;
|
||||
/**
|
||||
* 取消令牌
|
||||
*/
|
||||
cancelToken?: CancelToken
|
||||
cancelToken?: CancelToken;
|
||||
/**
|
||||
* 下载文件
|
||||
*/
|
||||
download?: boolean
|
||||
download?: boolean;
|
||||
/**
|
||||
* 上传文件
|
||||
*/
|
||||
upload?: boolean
|
||||
upload?: boolean;
|
||||
/**
|
||||
* 请求参数系列化函数
|
||||
*/
|
||||
paramsSerializer?: (params?: AnyObject) => string
|
||||
paramsSerializer?: (params?: AnyObject) => string;
|
||||
/**
|
||||
* 校验状态码
|
||||
*/
|
||||
validateStatus?: (status: number) => boolean
|
||||
validateStatus?: (status: number) => boolean;
|
||||
/**
|
||||
* 转换请求数据
|
||||
*/
|
||||
transformRequest?: AxiosTransformer<AxiosRequestData>
|
||||
transformRequest?: AxiosTransformer<AxiosRequestData>;
|
||||
/**
|
||||
* 转换响应数据
|
||||
*/
|
||||
transformResponse?: AxiosTransformer<AxiosResponseData>
|
||||
transformResponse?: AxiosTransformer<AxiosResponseData>;
|
||||
/**
|
||||
* 错误处理
|
||||
*/
|
||||
errorHandler?: (error: unknown) => Promise<AxiosResponse>
|
||||
errorHandler?: (error: unknown) => Promise<AxiosResponse>;
|
||||
/**
|
||||
* 监听下载进度
|
||||
*/
|
||||
onDownloadProgress?: AxiosUploadProgressCallback
|
||||
onDownloadProgress?: AxiosUploadProgressCallback;
|
||||
/**
|
||||
* 监听上传进度
|
||||
*/
|
||||
onUploadProgress?: AxiosUploadProgressCallback
|
||||
onUploadProgress?: AxiosUploadProgressCallback;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -248,27 +248,27 @@ export interface AxiosResponse<
|
|||
/**
|
||||
* 状态码
|
||||
*/
|
||||
status: number
|
||||
status: number;
|
||||
/**
|
||||
* 状态字符
|
||||
*/
|
||||
statusText: string
|
||||
statusText: string;
|
||||
/**
|
||||
* 响应头
|
||||
*/
|
||||
headers: AnyObject
|
||||
headers: AnyObject;
|
||||
/**
|
||||
* 响应数据
|
||||
*/
|
||||
data: TData
|
||||
data: TData;
|
||||
/**
|
||||
* 请求配置
|
||||
*/
|
||||
config: AxiosRequestConfig
|
||||
config: AxiosRequestConfig;
|
||||
/**
|
||||
* 请求任务
|
||||
*/
|
||||
request?: AxiosAdapterPlatformTask
|
||||
request?: AxiosAdapterPlatformTask;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -278,41 +278,41 @@ export interface AxiosResponseError extends AnyObject {
|
|||
/**
|
||||
* 状态码
|
||||
*/
|
||||
status: number
|
||||
status: number;
|
||||
/**
|
||||
* 状态字符
|
||||
*/
|
||||
statusText: string
|
||||
statusText: string;
|
||||
/**
|
||||
* 响应头
|
||||
*/
|
||||
headers: AnyObject
|
||||
headers: AnyObject;
|
||||
/**
|
||||
* 错误数据
|
||||
*/
|
||||
data: AnyObject
|
||||
data: AnyObject;
|
||||
/**
|
||||
* 失败的请求,指没能够成功响应的请求
|
||||
*/
|
||||
isFail: true
|
||||
isFail: true;
|
||||
/**
|
||||
* 请求配置
|
||||
*/
|
||||
config: AxiosRequestConfig
|
||||
config: AxiosRequestConfig;
|
||||
/**
|
||||
* 请求任务
|
||||
*/
|
||||
request?: AxiosAdapterPlatformTask
|
||||
request?: AxiosAdapterPlatformTask;
|
||||
}
|
||||
|
||||
export interface AxiosRequest {
|
||||
<TData extends AxiosResponseData>(config: AxiosRequestConfig): Promise<
|
||||
AxiosResponse<TData>
|
||||
>
|
||||
>;
|
||||
<TData extends AxiosResponseData>(
|
||||
url: string,
|
||||
config?: AxiosRequestConfig,
|
||||
): Promise<AxiosResponse<TData>>
|
||||
): Promise<AxiosResponse<TData>>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -321,7 +321,7 @@ export interface AxiosRequest {
|
|||
export type AxiosRequestMethodFn = <TData extends AxiosResponseData>(
|
||||
url: string,
|
||||
config?: AxiosRequestConfig,
|
||||
) => Promise<AxiosResponse<TData>>
|
||||
) => Promise<AxiosResponse<TData>>;
|
||||
|
||||
/**
|
||||
* 带参数的请求方法
|
||||
|
@ -330,7 +330,7 @@ export type AxiosRequestMethodFnWithParams = <TData extends AxiosResponseData>(
|
|||
url: string,
|
||||
params?: AnyObject,
|
||||
config?: AxiosRequestConfig,
|
||||
) => Promise<AxiosResponse<TData>>
|
||||
) => Promise<AxiosResponse<TData>>;
|
||||
|
||||
/**
|
||||
* 带数据的请求方法
|
||||
|
@ -339,29 +339,29 @@ export type AxiosRequestMethodFnWithData = <TData extends AxiosResponseData>(
|
|||
url: string,
|
||||
data?: AxiosRequestData,
|
||||
config?: AxiosRequestConfig,
|
||||
) => Promise<AxiosResponse<TData>>
|
||||
) => Promise<AxiosResponse<TData>>;
|
||||
|
||||
export interface AxiosDomainRequestHandler {
|
||||
(config: AxiosRequestConfig): Promise<AxiosResponse>
|
||||
(config: AxiosRequestConfig): Promise<AxiosResponse>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Axios 构造函数
|
||||
*/
|
||||
export interface AxiosConstructor {
|
||||
new (config: AxiosRequestConfig): Axios
|
||||
new (config: AxiosRequestConfig): Axios;
|
||||
}
|
||||
|
||||
export default class Axios {
|
||||
/**
|
||||
* 父级实例
|
||||
*/
|
||||
#parent?: Axios
|
||||
#parent?: Axios;
|
||||
|
||||
/**
|
||||
* 默认请求配置
|
||||
*/
|
||||
defaults: AxiosRequestConfig
|
||||
defaults: AxiosRequestConfig;
|
||||
|
||||
/**
|
||||
* 拦截器
|
||||
|
@ -375,57 +375,57 @@ export default class Axios {
|
|||
* 响应拦截器
|
||||
*/
|
||||
response: new InterceptorManager<AxiosResponse>(),
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 中间件
|
||||
*/
|
||||
#middleware = new MiddlewareManager()
|
||||
#middleware = new MiddlewareManager();
|
||||
|
||||
/**
|
||||
* 发送 options 请求
|
||||
*/
|
||||
options!: AxiosRequestMethodFn
|
||||
options!: AxiosRequestMethodFn;
|
||||
|
||||
/**
|
||||
* 发送 get 请求
|
||||
*/
|
||||
get!: AxiosRequestMethodFnWithParams
|
||||
get!: AxiosRequestMethodFnWithParams;
|
||||
|
||||
/**
|
||||
* 发送 head 请求
|
||||
*/
|
||||
head!: AxiosRequestMethodFnWithParams
|
||||
head!: AxiosRequestMethodFnWithParams;
|
||||
|
||||
/**
|
||||
* 发送 post 请求
|
||||
*/
|
||||
post!: AxiosRequestMethodFnWithData
|
||||
post!: AxiosRequestMethodFnWithData;
|
||||
|
||||
/**
|
||||
* 发送 put 请求
|
||||
*/
|
||||
put!: AxiosRequestMethodFnWithData
|
||||
put!: AxiosRequestMethodFnWithData;
|
||||
|
||||
/**
|
||||
* 发送 patch 请求
|
||||
*/
|
||||
patch!: AxiosRequestMethodFnWithData
|
||||
patch!: AxiosRequestMethodFnWithData;
|
||||
|
||||
/**
|
||||
* 发送 delete 请求
|
||||
*/
|
||||
delete!: AxiosRequestMethodFnWithParams
|
||||
delete!: AxiosRequestMethodFnWithParams;
|
||||
|
||||
/**
|
||||
* 发送 trace 请求
|
||||
*/
|
||||
trace!: AxiosRequestMethodFn
|
||||
trace!: AxiosRequestMethodFn;
|
||||
|
||||
/**
|
||||
* 发送 connect 请求
|
||||
*/
|
||||
connect!: AxiosRequestMethodFn
|
||||
connect!: AxiosRequestMethodFn;
|
||||
|
||||
/**
|
||||
*
|
||||
|
@ -433,8 +433,8 @@ export default class Axios {
|
|||
* @param parent 父级实例
|
||||
*/
|
||||
constructor(config: AxiosRequestConfig, parent?: Axios) {
|
||||
this.defaults = config
|
||||
this.#parent = parent
|
||||
this.defaults = config;
|
||||
this.#parent = parent;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -445,33 +445,33 @@ export default class Axios {
|
|||
config: AxiosRequestConfig = {},
|
||||
) => {
|
||||
if (isString(urlOrConfig)) {
|
||||
config.url = urlOrConfig
|
||||
config.url = urlOrConfig;
|
||||
} else {
|
||||
config = urlOrConfig
|
||||
config = urlOrConfig;
|
||||
}
|
||||
config = mergeConfig(this.defaults, config)
|
||||
config = mergeConfig(this.defaults, config);
|
||||
config.method = (config.method?.toLowerCase() ??
|
||||
'get') as AxiosRequestMethod
|
||||
'get') as AxiosRequestMethod;
|
||||
|
||||
const requestHandler = {
|
||||
resolved: this.#handleRequest,
|
||||
}
|
||||
};
|
||||
const errorHandler = {
|
||||
rejected: config.errorHandler,
|
||||
}
|
||||
};
|
||||
const chain: (
|
||||
| Partial<Interceptor<AxiosRequestConfig>>
|
||||
| Partial<Interceptor<AxiosResponse>>
|
||||
)[] = []
|
||||
)[] = [];
|
||||
|
||||
this.#eachRequestInterceptors((requestInterceptor) => {
|
||||
chain.unshift(requestInterceptor)
|
||||
})
|
||||
chain.push(requestHandler)
|
||||
chain.unshift(requestInterceptor);
|
||||
});
|
||||
chain.push(requestHandler);
|
||||
this.#eachResponseInterceptors((responseInterceptor) => {
|
||||
chain.push(responseInterceptor)
|
||||
})
|
||||
chain.push(errorHandler)
|
||||
chain.push(responseInterceptor);
|
||||
});
|
||||
chain.push(errorHandler);
|
||||
|
||||
return chain.reduce(
|
||||
(next, { resolved, rejected }) =>
|
||||
|
@ -481,20 +481,20 @@ export default class Axios {
|
|||
rejected,
|
||||
),
|
||||
Promise.resolve(config),
|
||||
) as Promise<AxiosResponse>
|
||||
}
|
||||
) as Promise<AxiosResponse>;
|
||||
};
|
||||
|
||||
#eachRequestInterceptors(executor: InterceptorExecutor<AxiosRequestConfig>) {
|
||||
this.interceptors.request.forEach(executor)
|
||||
this.interceptors.request.forEach(executor);
|
||||
if (this.#parent) {
|
||||
this.#parent.#eachRequestInterceptors(executor)
|
||||
this.#parent.#eachRequestInterceptors(executor);
|
||||
}
|
||||
}
|
||||
|
||||
#eachResponseInterceptors(executor: InterceptorExecutor<AxiosResponse>) {
|
||||
this.interceptors.response.forEach(executor)
|
||||
this.interceptors.response.forEach(executor);
|
||||
if (this.#parent) {
|
||||
this.#parent.#eachResponseInterceptors(executor)
|
||||
this.#parent.#eachResponseInterceptors(executor);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -504,48 +504,48 @@ export default class Axios {
|
|||
* @param middleware 中间件
|
||||
*/
|
||||
use = (middleware: MiddlewareCallback) => {
|
||||
this.#middleware.use(middleware)
|
||||
return this
|
||||
}
|
||||
this.#middleware.use(middleware);
|
||||
return this;
|
||||
};
|
||||
|
||||
#handleRequest = async (config: AxiosRequestConfig) => {
|
||||
const ctx = this.#middleware.createContext(config)
|
||||
await this.#run(ctx, this.#handleResponse)
|
||||
return ctx.res as AxiosResponse
|
||||
}
|
||||
const ctx = this.#middleware.createContext(config);
|
||||
await this.#run(ctx, this.#handleResponse);
|
||||
return ctx.res as AxiosResponse;
|
||||
};
|
||||
|
||||
#handleResponse = async (ctx: MiddlewareContext) => {
|
||||
ctx.res = await dispatchRequest(ctx.req)
|
||||
}
|
||||
ctx.res = await dispatchRequest(ctx.req);
|
||||
};
|
||||
|
||||
#run = (
|
||||
ctx: MiddlewareContext,
|
||||
respond: MiddlewareCallback,
|
||||
): Promise<void> => {
|
||||
if (!this.#parent) {
|
||||
return this.#middleware.run(ctx, respond)
|
||||
}
|
||||
return this.#middleware.enhanceRun(this.#parent.#run)(ctx, respond)
|
||||
return this.#middleware.run(ctx, respond);
|
||||
}
|
||||
return this.#middleware.enhanceRun(this.#parent.#run)(ctx, respond);
|
||||
};
|
||||
}
|
||||
|
||||
for (const method of PLAIN_METHODS) {
|
||||
Axios.prototype[method] = function processRequestMethod(url, config = {}) {
|
||||
config.method = method
|
||||
return this.request(url, config)
|
||||
}
|
||||
config.method = method;
|
||||
return this.request(url, config);
|
||||
};
|
||||
}
|
||||
|
||||
for (const method of WITH_PARAMS_METHODS) {
|
||||
Axios.prototype[method] = function processRequestMethodWithParams(
|
||||
url,
|
||||
params = {},
|
||||
params,
|
||||
config = {},
|
||||
) {
|
||||
config.method = method
|
||||
config.params = deepMerge(params, config.params ?? {})
|
||||
return this.request(url, config)
|
||||
}
|
||||
config.method = method;
|
||||
config.params = deepMerge(params, config.params);
|
||||
return this.request(url, config);
|
||||
};
|
||||
}
|
||||
|
||||
for (const method of WITH_DATA_METHODS) {
|
||||
|
@ -554,8 +554,8 @@ for (const method of WITH_DATA_METHODS) {
|
|||
data,
|
||||
config = {},
|
||||
) {
|
||||
config.method = method
|
||||
config.data = data
|
||||
return this.request(url, config)
|
||||
}
|
||||
config.method = method;
|
||||
config.data = data;
|
||||
return this.request(url, config);
|
||||
};
|
||||
}
|
||||
|
|
|
@ -1,9 +1,9 @@
|
|||
import { assert } from '../helpers/error'
|
||||
import { isFunction } from '../helpers/isTypes'
|
||||
import { AxiosRequestConfig, AxiosResponse } from './Axios'
|
||||
import { assert } from '../helpers/error';
|
||||
import { isFunction } from '../helpers/isTypes';
|
||||
import { AxiosRequestConfig, AxiosResponse } from './Axios';
|
||||
|
||||
export interface MiddlewareNext {
|
||||
(): Promise<void>
|
||||
(): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -15,18 +15,18 @@ export interface MiddlewareContext {
|
|||
*
|
||||
* 同于请求配置
|
||||
*/
|
||||
req: AxiosRequestConfig
|
||||
req: AxiosRequestConfig;
|
||||
/**
|
||||
* 响应体
|
||||
*/
|
||||
res: null | AxiosResponse
|
||||
res: null | AxiosResponse;
|
||||
}
|
||||
|
||||
/**
|
||||
* 中间件
|
||||
*/
|
||||
export interface MiddlewareCallback {
|
||||
(ctx: MiddlewareContext, next: MiddlewareNext): Promise<void>
|
||||
(ctx: MiddlewareContext, next: MiddlewareNext): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -36,7 +36,7 @@ export default class MiddlewareManager {
|
|||
/**
|
||||
* 中间件缓存池
|
||||
*/
|
||||
#middlewares: MiddlewareCallback[] = []
|
||||
#middlewares: MiddlewareCallback[] = [];
|
||||
|
||||
/**
|
||||
* 注册中间件
|
||||
|
@ -44,8 +44,8 @@ export default class MiddlewareManager {
|
|||
* @param middleware 中间件
|
||||
*/
|
||||
use(middleware: MiddlewareCallback) {
|
||||
assert(isFunction(middleware), 'middleware 不是一个 function')
|
||||
this.#middlewares.push(middleware)
|
||||
assert(isFunction(middleware), 'middleware 不是一个 function');
|
||||
this.#middlewares.push(middleware);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -55,7 +55,7 @@ export default class MiddlewareManager {
|
|||
return {
|
||||
req: config,
|
||||
res: null,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -65,11 +65,11 @@ export default class MiddlewareManager {
|
|||
* @param respond 目标函数
|
||||
*/
|
||||
run(ctx: MiddlewareContext, respond: MiddlewareCallback) {
|
||||
const middlewares = [...this.#middlewares, respond]
|
||||
const middlewares = [...this.#middlewares, respond];
|
||||
async function next() {
|
||||
await middlewares.shift()!(ctx, next)
|
||||
await middlewares.shift()!(ctx, next);
|
||||
}
|
||||
return next()
|
||||
return next();
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -79,7 +79,7 @@ export default class MiddlewareManager {
|
|||
*/
|
||||
enhanceRun(enhancer: MiddlewareManager['run']): MiddlewareManager['run'] {
|
||||
return (ctx, respond) => {
|
||||
return enhancer(ctx, () => this.run(ctx, respond))
|
||||
}
|
||||
return enhancer(ctx, () => this.run(ctx, respond));
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,15 +1,15 @@
|
|||
import { AxiosRequestConfig } from '../core/Axios'
|
||||
import { isPlainObject } from './isTypes'
|
||||
import { buildURL } from './buildURL'
|
||||
import { combineURL } from './combineURL'
|
||||
import { dynamicURL } from './dynamicURL'
|
||||
import { AxiosRequestConfig } from '../core/Axios';
|
||||
import { isPlainObject } from './isTypes';
|
||||
import { buildURL } from './buildURL';
|
||||
import { combineURL } from './combineURL';
|
||||
import { dynamicURL } from './dynamicURL';
|
||||
|
||||
export function transformURL(config: AxiosRequestConfig) {
|
||||
const fullPath = dynamicURL(
|
||||
combineURL(config.baseURL, config.url),
|
||||
config.params,
|
||||
isPlainObject(config.data) ? config.data : {},
|
||||
)
|
||||
);
|
||||
|
||||
return buildURL(fullPath, config.params, config.paramsSerializer)
|
||||
return buildURL(fullPath, config.params, config.paramsSerializer);
|
||||
}
|
||||
|
|
|
@ -1,12 +1,12 @@
|
|||
import { WITH_DATA_RE } from '../constants/methods'
|
||||
import { isFunction, isString } from '../helpers/isTypes'
|
||||
import { assert } from '../helpers/error'
|
||||
import { AxiosRequestConfig, AxiosResponse } from '../core/Axios'
|
||||
import { Cancel, isCancel, isCancelToken } from './cancel'
|
||||
import { flattenHeaders } from './flattenHeaders'
|
||||
import { AxiosTransformer, transformData } from './transformData'
|
||||
import { request } from './request'
|
||||
import { AxiosErrorResponse } from './createError'
|
||||
import { WITH_DATA_RE } from '../constants/methods';
|
||||
import { isFunction, isString } from '../helpers/isTypes';
|
||||
import { assert } from '../helpers/error';
|
||||
import { AxiosRequestConfig, AxiosResponse } from '../core/Axios';
|
||||
import { Cancel, isCancel, isCancelToken } from './cancel';
|
||||
import { flattenHeaders } from './flattenHeaders';
|
||||
import { AxiosTransformer, transformData } from './transformData';
|
||||
import { request } from './request';
|
||||
import { AxiosErrorResponse } from './createError';
|
||||
|
||||
/**
|
||||
* 发送请求
|
||||
|
@ -16,51 +16,51 @@ import { AxiosErrorResponse } from './createError'
|
|||
* @param config 请求配置
|
||||
*/
|
||||
export function dispatchRequest(config: AxiosRequestConfig) {
|
||||
throwIfCancellationRequested(config)
|
||||
throwIfCancellationRequested(config);
|
||||
|
||||
assert(isFunction(config.adapter), 'adapter 不是一个 function')
|
||||
assert(isString(config.url), 'url 不是一个 string')
|
||||
assert(isString(config.method), 'method 不是一个 string')
|
||||
assert(isFunction(config.adapter), 'adapter 不是一个 function');
|
||||
assert(isString(config.url), 'url 不是一个 string');
|
||||
assert(isString(config.method), 'method 不是一个 string');
|
||||
|
||||
config.headers = flattenHeaders(config)
|
||||
config.headers = flattenHeaders(config);
|
||||
|
||||
// 可以携带 data 的请求方法,转换 data
|
||||
// 否则,删除 data
|
||||
if (WITH_DATA_RE.test(config.method!)) {
|
||||
dataTransformer(config, config.transformRequest)
|
||||
dataTransformer(config, config.transformRequest);
|
||||
} else {
|
||||
delete config.data
|
||||
delete config.data;
|
||||
}
|
||||
|
||||
function onSuccess(response: AxiosResponse) {
|
||||
throwIfCancellationRequested(config)
|
||||
dataTransformer(response, config.transformResponse)
|
||||
throwIfCancellationRequested(config);
|
||||
dataTransformer(response, config.transformResponse);
|
||||
|
||||
return response
|
||||
return response;
|
||||
}
|
||||
|
||||
function onError(error: Cancel | AxiosErrorResponse) {
|
||||
if (!isCancel(error)) {
|
||||
throwIfCancellationRequested(config)
|
||||
dataTransformer(error.response, config.transformResponse)
|
||||
throwIfCancellationRequested(config);
|
||||
dataTransformer(error.response, config.transformResponse);
|
||||
}
|
||||
|
||||
return Promise.reject(error)
|
||||
return Promise.reject(error);
|
||||
}
|
||||
|
||||
function dataTransformer<TData = unknown>(
|
||||
obj: { data?: TData; headers?: AnyObject },
|
||||
fn?: AxiosTransformer<TData>,
|
||||
) {
|
||||
obj.data = transformData(obj.data, obj.headers, fn)
|
||||
obj.data = transformData(obj.data, obj.headers, fn);
|
||||
}
|
||||
|
||||
return request(config).then(onSuccess, onError)
|
||||
return request(config).then(onSuccess, onError);
|
||||
}
|
||||
|
||||
function throwIfCancellationRequested(config: AxiosRequestConfig) {
|
||||
const { cancelToken } = config
|
||||
const { cancelToken } = config;
|
||||
if (isCancelToken(cancelToken)) {
|
||||
cancelToken.throwIfRequested()
|
||||
cancelToken.throwIfRequested();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,20 +1,20 @@
|
|||
import { isFunction, isPlainObject } from '../helpers/isTypes'
|
||||
import { transformURL } from '../helpers/transformURL'
|
||||
import { isFunction, isPlainObject } from '../helpers/isTypes';
|
||||
import { transformURL } from '../helpers/transformURL';
|
||||
import {
|
||||
AxiosRequestConfig,
|
||||
AxiosResponse,
|
||||
AxiosResponseError,
|
||||
} from '../core/Axios'
|
||||
} from '../core/Axios';
|
||||
import {
|
||||
AxiosAdapterRequestConfig,
|
||||
AxiosAdapterResponse,
|
||||
AxiosAdapterResponseError,
|
||||
AxiosAdapterPlatformTask,
|
||||
AxiosAdapterRequestMethod,
|
||||
} from '../adpater/createAdapter'
|
||||
import { isCancelToken } from './cancel'
|
||||
import { AxiosErrorResponse, createError } from './createError'
|
||||
import { generateType } from './generateType'
|
||||
} from '../adpater/createAdapter';
|
||||
import { isCancelToken } from './cancel';
|
||||
import { AxiosErrorResponse, createError } from './createError';
|
||||
import { generateType } from './generateType';
|
||||
|
||||
/**
|
||||
* 开始请求
|
||||
|
@ -32,91 +32,91 @@ export function request(config: AxiosRequestConfig) {
|
|||
method: config.method!.toUpperCase() as AxiosAdapterRequestMethod,
|
||||
success,
|
||||
fail,
|
||||
}
|
||||
};
|
||||
|
||||
let adapterTask: AxiosAdapterPlatformTask
|
||||
let adapterTask: AxiosAdapterPlatformTask;
|
||||
try {
|
||||
adapterTask = config.adapter!(adapterConfig)
|
||||
adapterTask = config.adapter!(adapterConfig);
|
||||
} catch (err) {
|
||||
fail({
|
||||
status: 400,
|
||||
statusText: 'Bad Adapter',
|
||||
})
|
||||
});
|
||||
|
||||
console.error(err)
|
||||
console.error(err);
|
||||
}
|
||||
|
||||
function success(baseResponse: AxiosAdapterResponse): void {
|
||||
const response = baseResponse as AxiosResponse
|
||||
response.status = response.status ?? 200
|
||||
response.statusText = response.statusText ?? 'OK'
|
||||
response.headers = response.headers ?? {}
|
||||
response.config = config
|
||||
response.request = adapterTask
|
||||
const response = baseResponse as AxiosResponse;
|
||||
response.status = response.status ?? 200;
|
||||
response.statusText = response.statusText ?? 'OK';
|
||||
response.headers = response.headers ?? {};
|
||||
response.config = config;
|
||||
response.request = adapterTask;
|
||||
|
||||
const { validateStatus } = config
|
||||
const { validateStatus } = config;
|
||||
if (!isFunction(validateStatus) || validateStatus(response.status)) {
|
||||
resolve(response)
|
||||
resolve(response);
|
||||
} else {
|
||||
catchError('validate status error', response)
|
||||
catchError('validate status error', response);
|
||||
}
|
||||
}
|
||||
|
||||
function fail(baseResponseError: AxiosAdapterResponseError): void {
|
||||
const responseError = baseResponseError as AxiosResponseError
|
||||
responseError.isFail = true
|
||||
responseError.status = responseError.status ?? 400
|
||||
responseError.statusText = responseError.statusText ?? 'Fail'
|
||||
responseError.headers = responseError.headers ?? {}
|
||||
responseError.config = config
|
||||
responseError.request = adapterTask
|
||||
const responseError = baseResponseError as AxiosResponseError;
|
||||
responseError.isFail = true;
|
||||
responseError.status = responseError.status ?? 400;
|
||||
responseError.statusText = responseError.statusText ?? 'Fail';
|
||||
responseError.headers = responseError.headers ?? {};
|
||||
responseError.config = config;
|
||||
responseError.request = adapterTask;
|
||||
|
||||
catchError('request fail', responseError)
|
||||
catchError('request fail', responseError);
|
||||
}
|
||||
|
||||
function catchError(
|
||||
message: string,
|
||||
errorResponse: AxiosErrorResponse,
|
||||
): void {
|
||||
reject(createError(message, config, errorResponse, adapterTask))
|
||||
reject(createError(message, config, errorResponse, adapterTask));
|
||||
}
|
||||
|
||||
if (isPlainObject(adapterTask)) {
|
||||
tryToggleProgressUpdate(adapterConfig, adapterTask.onProgressUpdate)
|
||||
tryToggleProgressUpdate(adapterConfig, adapterTask.onProgressUpdate);
|
||||
}
|
||||
|
||||
const { cancelToken } = config
|
||||
const { cancelToken } = config;
|
||||
if (isCancelToken(cancelToken)) {
|
||||
cancelToken.onCancel((reason) => {
|
||||
if (isPlainObject(adapterTask)) {
|
||||
tryToggleProgressUpdate(adapterConfig, adapterTask.offProgressUpdate)
|
||||
tryToggleProgressUpdate(adapterConfig, adapterTask.offProgressUpdate);
|
||||
|
||||
adapterTask?.abort?.()
|
||||
adapterTask?.abort?.();
|
||||
}
|
||||
|
||||
reject(reason)
|
||||
})
|
||||
reject(reason);
|
||||
});
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
function tryToggleProgressUpdate(
|
||||
config: AxiosAdapterRequestConfig,
|
||||
progress?: (cb: (event: AnyObject) => void) => void,
|
||||
) {
|
||||
const { type, onUploadProgress, onDownloadProgress } = config
|
||||
const { type, onUploadProgress, onDownloadProgress } = config;
|
||||
if (isFunction(progress)) {
|
||||
switch (type) {
|
||||
case 'upload':
|
||||
if (isFunction(onUploadProgress)) {
|
||||
progress(onUploadProgress)
|
||||
progress(onUploadProgress);
|
||||
}
|
||||
break
|
||||
break;
|
||||
case 'download':
|
||||
if (isFunction(onDownloadProgress)) {
|
||||
progress(onDownloadProgress)
|
||||
progress(onDownloadProgress);
|
||||
}
|
||||
break
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1 +1 @@
|
|||
export const version = '2.4.1'
|
||||
export const version = '2.4.1';
|
||||
|
|
|
@ -1,14 +1,14 @@
|
|||
import { describe, test, expect, vi } from 'vitest'
|
||||
import { asyncNext, mockAdapter } from 'scripts/test.utils'
|
||||
import { describe, test, expect, vi } from 'vitest';
|
||||
import { asyncNext, mockAdapter } from 'scripts/test.utils';
|
||||
import {
|
||||
PLAIN_METHODS,
|
||||
WITH_DATA_METHODS,
|
||||
WITH_PARAMS_METHODS,
|
||||
} from '@/constants/methods'
|
||||
import { dispatchRequest } from '@/request/dispatchRequest'
|
||||
} from '@/constants/methods';
|
||||
import { dispatchRequest } from '@/request/dispatchRequest';
|
||||
|
||||
import axios from '@/axios'
|
||||
import _defaults from '@/defaults'
|
||||
import axios from '@/axios';
|
||||
import _defaults from '@/defaults';
|
||||
|
||||
describe('src/request/dispatchRequest.ts', () => {
|
||||
const defaults = {
|
||||
|
@ -17,32 +17,32 @@ describe('src/request/dispatchRequest.ts', () => {
|
|||
baseURL: 'http://api.com',
|
||||
method: 'get' as const,
|
||||
headers: {},
|
||||
}
|
||||
};
|
||||
|
||||
test('应该抛出异常', () => {
|
||||
expect(() => dispatchRequest({})).toThrowErrorMatchingInlineSnapshot(
|
||||
'"[axios-miniprogram]: adapter 不是一个 function"',
|
||||
)
|
||||
);
|
||||
expect(() =>
|
||||
dispatchRequest({ adapter: mockAdapter() }),
|
||||
).toThrowErrorMatchingInlineSnapshot(
|
||||
'"[axios-miniprogram]: url 不是一个 string"',
|
||||
)
|
||||
);
|
||||
expect(() =>
|
||||
dispatchRequest({ adapter: mockAdapter(), url: '/' }),
|
||||
).toThrowErrorMatchingInlineSnapshot(
|
||||
'"[axios-miniprogram]: method 不是一个 string"',
|
||||
)
|
||||
);
|
||||
expect(() =>
|
||||
dispatchRequest({ adapter: mockAdapter(), url: '/', method: 'get' }),
|
||||
).not.toThrowError()
|
||||
})
|
||||
).not.toThrowError();
|
||||
});
|
||||
|
||||
test('坏的适配器应该抛出异常', () => {
|
||||
expect(
|
||||
dispatchRequest({
|
||||
adapter: () => {
|
||||
throw 'bad adapter'
|
||||
throw 'bad adapter';
|
||||
},
|
||||
url: '/',
|
||||
method: 'get',
|
||||
|
@ -71,8 +71,8 @@ describe('src/request/dispatchRequest.ts', () => {
|
|||
"statusText": "Bad Adapter",
|
||||
},
|
||||
}
|
||||
`)
|
||||
})
|
||||
`);
|
||||
});
|
||||
|
||||
test('应该支持拉平请求头', () => {
|
||||
const c = {
|
||||
|
@ -87,16 +87,16 @@ describe('src/request/dispatchRequest.ts', () => {
|
|||
},
|
||||
h3: 3,
|
||||
},
|
||||
}
|
||||
};
|
||||
|
||||
dispatchRequest(c)
|
||||
dispatchRequest(c);
|
||||
|
||||
expect(c.headers).toEqual({
|
||||
h1: 1,
|
||||
h2: 2,
|
||||
h3: 3,
|
||||
})
|
||||
})
|
||||
});
|
||||
});
|
||||
|
||||
test.each(WITH_DATA_METHODS)('%s 方法应该支持转换请求数据', (k) => {
|
||||
const c = {
|
||||
|
@ -105,12 +105,12 @@ describe('src/request/dispatchRequest.ts', () => {
|
|||
method: k,
|
||||
data: {},
|
||||
transformRequest: () => ({ id: 1 }),
|
||||
}
|
||||
};
|
||||
|
||||
dispatchRequest(c)
|
||||
dispatchRequest(c);
|
||||
|
||||
expect(c.data).toEqual({ id: 1 })
|
||||
})
|
||||
expect(c.data).toEqual({ id: 1 });
|
||||
});
|
||||
|
||||
test('不能带数据的请求方法应该删除数据', () => {
|
||||
const c = {
|
||||
|
@ -118,66 +118,66 @@ describe('src/request/dispatchRequest.ts', () => {
|
|||
url: 'test',
|
||||
data: {},
|
||||
transformRequest: () => ({ id: 1 }),
|
||||
}
|
||||
};
|
||||
|
||||
;[...PLAIN_METHODS, ...WITH_PARAMS_METHODS].forEach((k) => {
|
||||
const s = { ...c, method: k }
|
||||
dispatchRequest(s)
|
||||
expect(s.data).toBeUndefined()
|
||||
})
|
||||
})
|
||||
[...PLAIN_METHODS, ...WITH_PARAMS_METHODS].forEach((k) => {
|
||||
const s = { ...c, method: k };
|
||||
dispatchRequest(s);
|
||||
expect(s.data).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
test('应该支持转换响应数据', async () => {
|
||||
const c = {
|
||||
...defaults,
|
||||
url: 'test',
|
||||
transformResponse: () => ({ result: 1 }),
|
||||
}
|
||||
};
|
||||
|
||||
const r = await dispatchRequest(c)
|
||||
const r = await dispatchRequest(c);
|
||||
|
||||
expect(r.data).toEqual({ result: 1 })
|
||||
})
|
||||
expect(r.data).toEqual({ result: 1 });
|
||||
});
|
||||
|
||||
test('请求发送前取消请求应该抛出异常', async () => {
|
||||
const cb = vi.fn()
|
||||
const { cancel, token } = axios.CancelToken.source()
|
||||
const cb = vi.fn();
|
||||
const { cancel, token } = axios.CancelToken.source();
|
||||
const c = {
|
||||
...defaults,
|
||||
url: 'test',
|
||||
cancelToken: token,
|
||||
}
|
||||
};
|
||||
|
||||
cancel()
|
||||
cancel();
|
||||
|
||||
try {
|
||||
dispatchRequest(c)
|
||||
dispatchRequest(c);
|
||||
} catch (err) {
|
||||
cb(err)
|
||||
cb(err);
|
||||
}
|
||||
|
||||
expect(cb).toBeCalled()
|
||||
expect(axios.isCancel(cb.mock.calls[0][0])).toBeTruthy()
|
||||
})
|
||||
expect(cb).toBeCalled();
|
||||
expect(axios.isCancel(cb.mock.calls[0][0])).toBeTruthy();
|
||||
});
|
||||
|
||||
test('请求发送后取消请求应该抛出异常', async () => {
|
||||
const cb = vi.fn()
|
||||
const { cancel, token } = axios.CancelToken.source()
|
||||
const cb = vi.fn();
|
||||
const { cancel, token } = axios.CancelToken.source();
|
||||
const c = {
|
||||
...defaults,
|
||||
url: 'test',
|
||||
cancelToken: token,
|
||||
}
|
||||
};
|
||||
|
||||
const p = dispatchRequest(c).catch(cb)
|
||||
const p = dispatchRequest(c).catch(cb);
|
||||
|
||||
await asyncNext()
|
||||
expect(cb).not.toBeCalled()
|
||||
await asyncNext();
|
||||
expect(cb).not.toBeCalled();
|
||||
|
||||
cancel()
|
||||
await p
|
||||
cancel();
|
||||
await p;
|
||||
|
||||
expect(cb).toBeCalled()
|
||||
expect(axios.isCancel(cb.mock.calls[0][0])).toBeTruthy()
|
||||
})
|
||||
})
|
||||
expect(cb).toBeCalled();
|
||||
expect(axios.isCancel(cb.mock.calls[0][0])).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
|
Loading…
Reference in New Issue