docs: 初始化示例项目

pull/49/head
zjx0905 2023-05-05 10:59:37 +08:00
parent 74856f7fde
commit 359b09172e
36 changed files with 8834 additions and 1159 deletions

View File

@ -1,4 +1,5 @@
{ {
"root": true,
"env": { "env": {
"es2022": true, "es2022": true,
"node": true "node": true
@ -6,10 +7,10 @@
"extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended"], "extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended"],
"parser": "@typescript-eslint/parser", "parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint"], "plugins": ["@typescript-eslint"],
"root": true,
"rules": { "rules": {
"@typescript-eslint/no-explicit-any": 0, "@typescript-eslint/no-explicit-any": 0,
"@typescript-eslint/no-non-null-assertion": 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
} }
} }

View File

@ -44,7 +44,7 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with: with:
tag_name: ${{ github.ref }} tag_name: ${{ github.ref }}
name: Release ${{ github.ref }} name: Release ${{ github.ref_name }}
prerelease: ${{ steps.prerelease.outputs.result }} prerelease: ${{ steps.prerelease.outputs.result }}
body_path: 'RELEASELOG.md' body_path: 'RELEASELOG.md'
files: 'dist/**.zip' files: 'dist/**.zip'

View File

@ -1 +1,2 @@
CHANGELOG.md CHANGELOG.md
dist/

View File

@ -1,11 +1,10 @@
{ {
"printWidth": 80, "printWidth": 80,
"tabWidth": 2, "tabWidth": 2,
"useTabs": true, "useTabs": false,
"semi": false, "semi": true,
"singleQuote": true, "singleQuote": true,
"trailingComma": "all", "trailingComma": "all",
"bracketSpacing": true, "bracketSpacing": true,
"arrowParens": "always", "arrowParens": "always"
"jsxSingleQuote": true
} }

11
example/.babelrc Normal file
View File

@ -0,0 +1,11 @@
{
"presets": [
[
"taro",
{
"framework": "vue3",
"ts": true
}
]
]
}

11
example/.eslintrc Normal file
View File

@ -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"
}
}

8
example/.gitignore vendored Normal file
View File

@ -0,0 +1,8 @@
dist/
deploy_versions/
.temp/
.rn_temp/
node_modules/
.DS_Store
.swc
config/**.js

2
example/.prettierignore Normal file
View File

@ -0,0 +1,2 @@
dist/
config/**.js

View File

@ -0,0 +1,8 @@
export default {
env: {
NODE_ENV: '"development"',
},
defineConstants: {},
mini: {},
h5: {},
};

View File

@ -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
},
},
},
};

View File

@ -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') })
// }))
// }
},
};

31
example/global.d.ts vendored Normal file
View File

@ -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';
}

58
example/package.json Normal file
View File

@ -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"
}
}

View File

@ -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"
}

9
example/project.tt.json Normal file
View File

@ -0,0 +1,9 @@
{
"miniprogramRoot": "./",
"projectname": "axios-miniprogram",
"appid": "testAppId",
"setting": {
"es6": false,
"minified": false
}
}

View File

@ -0,0 +1,9 @@
export default defineAppConfig({
pages: ['pages/index/index'],
window: {
backgroundTextStyle: 'light',
navigationBarBackgroundColor: '#fff',
navigationBarTitleText: 'axios-miniprogram',
navigationBarTextStyle: 'black',
},
});

0
example/src/app.css Normal file
View File

4
example/src/app.ts Normal file
View File

@ -0,0 +1,4 @@
import { createApp } from 'vue';
import './app.css';
export default createApp({});

17
example/src/index.html Normal file
View File

@ -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>

View File

@ -0,0 +1,3 @@
export default definePageConfig({
navigationBarTitleText: '首页',
});

View File

View File

@ -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>

18
example/tsconfig.json Normal file
View File

@ -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"]
}

View File

@ -47,7 +47,8 @@
"docs:build": "pnpm -C docs build", "docs:build": "pnpm -C docs build",
"docs:preview": "pnpm -C docs preview", "docs:preview": "pnpm -C docs preview",
"docs:deploy": "esno scripts/docs.deploy.ts", "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": { "devDependencies": {
"@commitlint/cli": "^17.4.4", "@commitlint/cli": "^17.4.4",
@ -90,7 +91,7 @@
} }
}, },
"lint-staged": { "lint-staged": {
"*.{mjs,json}": [ "*.{js,json}": [
"prettier --write" "prettier --write"
], ],
"*.ts?(x)": [ "*.ts?(x)": [
@ -103,7 +104,8 @@
"ignoreMissing": [ "ignoreMissing": [
"@algolia/client-search", "@algolia/client-search",
"esbuild", "esbuild",
"vite" "vite",
"eslint"
] ]
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,2 +1,3 @@
packages: packages:
- docs - docs
- example

View File

@ -1,34 +1,34 @@
import minimist from 'minimist' import minimist from 'minimist';
import consola from 'consola' import consola from 'consola';
import { distPath, exec } from './utils' import { distPath, exec } from './utils';
import { checkSize } from './checkSize' import { checkSize } from './checkSize';
import { safeExit } from './utils' import { safeExit } from './utils';
const args = minimist(process.argv.slice(2)) const args = minimist(process.argv.slice(2));
const watch = Boolean(args.watch || args.w) const watch = Boolean(args.watch || args.w);
const all = Boolean(args.all || args.a) const all = Boolean(args.all || args.a);
const sourceMap = all || Boolean(args.sourceMap || args.s) const sourceMap = all || Boolean(args.sourceMap || args.s);
const dts = all || Boolean(args.dts || args.d) const dts = all || Boolean(args.dts || args.d);
main() main();
function main() { function main() {
exec('rimraf dist') exec('rimraf dist');
consola.info('Rollup') consola.info('Rollup');
safeExit(() => { safeExit(() => {
exec( exec(
`rollup -c rollup.config.ts --configPlugin typescript ${ `rollup -c rollup.config.ts --configPlugin typescript ${
watch ? '-w' : '' watch ? '-w' : ''
} --environment SOURCE_MAP:${sourceMap},DTS:${dts}`, } --environment SOURCE_MAP:${sourceMap},DTS:${dts}`,
) );
}) });
if (!watch) { if (!watch) {
checkSize(`${distPath}/**.js`) checkSize(`${distPath}/**.js`);
} }
console.info('\n') console.info('\n');
} }

View File

@ -1,8 +1,27 @@
import enquirer from 'enquirer' import enquirer from 'enquirer';
import { exec } from './utils' import { exec, resolve } from './utils';
import { safeExit } 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: 'weapp', message: '微信小程序' },
{ name: 'swan', message: '百度小程序' }, { name: 'swan', message: '百度小程序' },
{ name: 'alipay', message: '支付宝小程序' }, { name: 'alipay', message: '支付宝小程序' },
@ -13,17 +32,5 @@ const metas = [
{ name: 'lark', message: '飞书小程序' }, { name: 'lark', message: '飞书小程序' },
{ name: 'kwai', message: '快手小程序' }, { name: 'kwai', message: '快手小程序' },
{ name: 'h5', message: 'H5' }, { 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}`)
} }

View File

@ -1,39 +1,40 @@
import { isPromise } from 'node:util/types' import { isPromise } from 'node:util/types';
import path from 'node:path' import path from 'node:path';
import { createRequire } from 'node:module' import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url' import { fileURLToPath } from 'node:url';
import { ExecSyncOptions, execSync } from 'node:child_process' import { ExecSyncOptions, execSync } from 'node:child_process';
import consola from 'consola' import consola from 'consola';
export const __dirname = fileURLToPath(new URL('../', import.meta.url)) export const __dirname = fileURLToPath(new URL('../', import.meta.url));
export const require = createRequire(import.meta.url) export const require = createRequire(import.meta.url);
export const pkgPath = path.resolve(__dirname, 'package.json') export const pkgPath = path.resolve(__dirname, 'package.json');
export const distPath = path.resolve(__dirname, 'dist') 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 = {}) => export const exec = (command: string, options: ExecSyncOptions = {}) =>
execSync(command, { execSync(command, {
stdio: 'inherit', stdio: 'inherit',
encoding: 'utf-8', encoding: 'utf-8',
...options, ...options,
}) });
export const getPkgJSON = () => require(pkgPath) export const getPkgJSON = () => require(pkgPath);
export function safeExit(run: () => unknown) { export function safeExit(run: () => unknown) {
try { try {
const p = run() const p = run();
if (isPromise(p)) { if (isPromise(p)) {
return p.catch(exit) return p.catch(exit);
} }
} catch { } catch {
exit() exit();
} }
} }
function exit() { function exit() {
consola.error('已退出') consola.error('已退出');
process.exit() process.exit();
} }

View File

@ -2,28 +2,28 @@ import {
PLAIN_METHODS, PLAIN_METHODS,
WITH_DATA_METHODS, WITH_DATA_METHODS,
WITH_PARAMS_METHODS, WITH_PARAMS_METHODS,
} from '../constants/methods' } from '../constants/methods';
import { isString } from '../helpers/isTypes' import { isString } from '../helpers/isTypes';
import { dispatchRequest } from '../request/dispatchRequest' import { dispatchRequest } from '../request/dispatchRequest';
import { CancelToken } from '../request/cancel' import { CancelToken } from '../request/cancel';
import { AxiosTransformer } from '../request/transformData' import { AxiosTransformer } from '../request/transformData';
import { deepMerge } from '../helpers/deepMerge' import { deepMerge } from '../helpers/deepMerge';
import { import {
AxiosAdapter, AxiosAdapter,
AxiosAdapterRequestMethod, AxiosAdapterRequestMethod,
AxiosAdapterPlatformTask, AxiosAdapterPlatformTask,
AxiosAdapterRequestConfig, AxiosAdapterRequestConfig,
AxiosAdapterResponseData, AxiosAdapterResponseData,
} from '../adpater/createAdapter' } from '../adpater/createAdapter';
import InterceptorManager, { import InterceptorManager, {
Interceptor, Interceptor,
InterceptorExecutor, InterceptorExecutor,
} from './InterceptorManager' } from './InterceptorManager';
import MiddlewareManager, { import MiddlewareManager, {
MiddlewareCallback, MiddlewareCallback,
MiddlewareContext, MiddlewareContext,
} from './MiddlewareManager' } from './MiddlewareManager';
import { mergeConfig } from './mergeConfig' import { mergeConfig } from './mergeConfig';
/** /**
* *
@ -38,7 +38,7 @@ export type AxiosRequestMethod =
| 'patch' | 'patch'
| 'delete' | 'delete'
| 'trace' | 'trace'
| 'connect' | 'connect';
/** /**
* *
@ -47,39 +47,39 @@ export interface AxiosRequestHeaders extends AnyObject {
/** /**
* *
*/ */
common?: AnyObject common?: AnyObject;
/** /**
* options * options
*/ */
options?: AnyObject options?: AnyObject;
/** /**
* get * get
*/ */
get?: AnyObject get?: AnyObject;
/** /**
* head * head
*/ */
head?: AnyObject head?: AnyObject;
/** /**
* post * post
*/ */
post?: AnyObject post?: AnyObject;
/** /**
* put * put
*/ */
put?: AnyObject put?: AnyObject;
/** /**
* delete * delete
*/ */
delete?: AnyObject delete?: AnyObject;
/** /**
* trace * trace
*/ */
trace?: AnyObject trace?: AnyObject;
/** /**
* connect * 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 | string
| AnyObject | AnyObject
| ArrayBuffer | 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 * Bytes
*/ */
totalBytesWritten: number totalBytesWritten: number;
/** /**
* Bytes * Bytes
*/ */
totalBytesExpectedToWrite: number totalBytesExpectedToWrite: number;
} }
/** /**
* *
*/ */
export interface AxiosDownloadProgressCallback { export interface AxiosDownloadProgressCallback {
(event: AxiosDownloadProgressEvent): void (event: AxiosDownloadProgressEvent): void;
} }
/** /**
@ -148,18 +148,18 @@ export interface AxiosUploadProgressEvent extends AxiosProgressEvent {
/** /**
* Bytes * Bytes
*/ */
totalBytesSent: number totalBytesSent: number;
/** /**
* Bytes * Bytes
*/ */
totalBytesExpectedToSend: number totalBytesExpectedToSend: number;
} }
/** /**
* *
*/ */
export interface AxiosUploadProgressCallback { 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
*/ */
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 { export interface AxiosRequest {
<TData extends AxiosResponseData>(config: AxiosRequestConfig): Promise< <TData extends AxiosResponseData>(config: AxiosRequestConfig): Promise<
AxiosResponse<TData> AxiosResponse<TData>
> >;
<TData extends AxiosResponseData>( <TData extends AxiosResponseData>(
url: string, url: string,
config?: AxiosRequestConfig, config?: AxiosRequestConfig,
): Promise<AxiosResponse<TData>> ): Promise<AxiosResponse<TData>>;
} }
/** /**
@ -321,7 +321,7 @@ export interface AxiosRequest {
export type AxiosRequestMethodFn = <TData extends AxiosResponseData>( export type AxiosRequestMethodFn = <TData extends AxiosResponseData>(
url: string, url: string,
config?: AxiosRequestConfig, config?: AxiosRequestConfig,
) => Promise<AxiosResponse<TData>> ) => Promise<AxiosResponse<TData>>;
/** /**
* *
@ -330,7 +330,7 @@ export type AxiosRequestMethodFnWithParams = <TData extends AxiosResponseData>(
url: string, url: string,
params?: AnyObject, params?: AnyObject,
config?: AxiosRequestConfig, config?: AxiosRequestConfig,
) => Promise<AxiosResponse<TData>> ) => Promise<AxiosResponse<TData>>;
/** /**
* *
@ -339,29 +339,29 @@ export type AxiosRequestMethodFnWithData = <TData extends AxiosResponseData>(
url: string, url: string,
data?: AxiosRequestData, data?: AxiosRequestData,
config?: AxiosRequestConfig, config?: AxiosRequestConfig,
) => Promise<AxiosResponse<TData>> ) => Promise<AxiosResponse<TData>>;
export interface AxiosDomainRequestHandler { export interface AxiosDomainRequestHandler {
(config: AxiosRequestConfig): Promise<AxiosResponse> (config: AxiosRequestConfig): Promise<AxiosResponse>;
} }
/** /**
* Axios * Axios
*/ */
export interface AxiosConstructor { export interface AxiosConstructor {
new (config: AxiosRequestConfig): Axios new (config: AxiosRequestConfig): Axios;
} }
export default class 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>(), response: new InterceptorManager<AxiosResponse>(),
} };
/** /**
* *
*/ */
#middleware = new MiddlewareManager() #middleware = new MiddlewareManager();
/** /**
* options * options
*/ */
options!: AxiosRequestMethodFn options!: AxiosRequestMethodFn;
/** /**
* get * get
*/ */
get!: AxiosRequestMethodFnWithParams get!: AxiosRequestMethodFnWithParams;
/** /**
* head * head
*/ */
head!: AxiosRequestMethodFnWithParams head!: AxiosRequestMethodFnWithParams;
/** /**
* post * post
*/ */
post!: AxiosRequestMethodFnWithData post!: AxiosRequestMethodFnWithData;
/** /**
* put * put
*/ */
put!: AxiosRequestMethodFnWithData put!: AxiosRequestMethodFnWithData;
/** /**
* patch * patch
*/ */
patch!: AxiosRequestMethodFnWithData patch!: AxiosRequestMethodFnWithData;
/** /**
* delete * delete
*/ */
delete!: AxiosRequestMethodFnWithParams delete!: AxiosRequestMethodFnWithParams;
/** /**
* trace * trace
*/ */
trace!: AxiosRequestMethodFn trace!: AxiosRequestMethodFn;
/** /**
* connect * connect
*/ */
connect!: AxiosRequestMethodFn connect!: AxiosRequestMethodFn;
/** /**
* *
@ -433,8 +433,8 @@ export default class Axios {
* @param parent * @param parent
*/ */
constructor(config: AxiosRequestConfig, parent?: Axios) { constructor(config: AxiosRequestConfig, parent?: Axios) {
this.defaults = config this.defaults = config;
this.#parent = parent this.#parent = parent;
} }
/** /**
@ -445,33 +445,33 @@ export default class Axios {
config: AxiosRequestConfig = {}, config: AxiosRequestConfig = {},
) => { ) => {
if (isString(urlOrConfig)) { if (isString(urlOrConfig)) {
config.url = urlOrConfig config.url = urlOrConfig;
} else { } else {
config = urlOrConfig config = urlOrConfig;
} }
config = mergeConfig(this.defaults, config) config = mergeConfig(this.defaults, config);
config.method = (config.method?.toLowerCase() ?? config.method = (config.method?.toLowerCase() ??
'get') as AxiosRequestMethod 'get') as AxiosRequestMethod;
const requestHandler = { const requestHandler = {
resolved: this.#handleRequest, resolved: this.#handleRequest,
} };
const errorHandler = { const errorHandler = {
rejected: config.errorHandler, rejected: config.errorHandler,
} };
const chain: ( const chain: (
| Partial<Interceptor<AxiosRequestConfig>> | Partial<Interceptor<AxiosRequestConfig>>
| Partial<Interceptor<AxiosResponse>> | Partial<Interceptor<AxiosResponse>>
)[] = [] )[] = [];
this.#eachRequestInterceptors((requestInterceptor) => { this.#eachRequestInterceptors((requestInterceptor) => {
chain.unshift(requestInterceptor) chain.unshift(requestInterceptor);
}) });
chain.push(requestHandler) chain.push(requestHandler);
this.#eachResponseInterceptors((responseInterceptor) => { this.#eachResponseInterceptors((responseInterceptor) => {
chain.push(responseInterceptor) chain.push(responseInterceptor);
}) });
chain.push(errorHandler) chain.push(errorHandler);
return chain.reduce( return chain.reduce(
(next, { resolved, rejected }) => (next, { resolved, rejected }) =>
@ -481,20 +481,20 @@ export default class Axios {
rejected, rejected,
), ),
Promise.resolve(config), Promise.resolve(config),
) as Promise<AxiosResponse> ) as Promise<AxiosResponse>;
} };
#eachRequestInterceptors(executor: InterceptorExecutor<AxiosRequestConfig>) { #eachRequestInterceptors(executor: InterceptorExecutor<AxiosRequestConfig>) {
this.interceptors.request.forEach(executor) this.interceptors.request.forEach(executor);
if (this.#parent) { if (this.#parent) {
this.#parent.#eachRequestInterceptors(executor) this.#parent.#eachRequestInterceptors(executor);
} }
} }
#eachResponseInterceptors(executor: InterceptorExecutor<AxiosResponse>) { #eachResponseInterceptors(executor: InterceptorExecutor<AxiosResponse>) {
this.interceptors.response.forEach(executor) this.interceptors.response.forEach(executor);
if (this.#parent) { if (this.#parent) {
this.#parent.#eachResponseInterceptors(executor) this.#parent.#eachResponseInterceptors(executor);
} }
} }
@ -504,48 +504,48 @@ export default class Axios {
* @param middleware * @param middleware
*/ */
use = (middleware: MiddlewareCallback) => { use = (middleware: MiddlewareCallback) => {
this.#middleware.use(middleware) this.#middleware.use(middleware);
return this return this;
} };
#handleRequest = async (config: AxiosRequestConfig) => { #handleRequest = async (config: AxiosRequestConfig) => {
const ctx = this.#middleware.createContext(config) const ctx = this.#middleware.createContext(config);
await this.#run(ctx, this.#handleResponse) await this.#run(ctx, this.#handleResponse);
return ctx.res as AxiosResponse return ctx.res as AxiosResponse;
} };
#handleResponse = async (ctx: MiddlewareContext) => { #handleResponse = async (ctx: MiddlewareContext) => {
ctx.res = await dispatchRequest(ctx.req) ctx.res = await dispatchRequest(ctx.req);
} };
#run = ( #run = (
ctx: MiddlewareContext, ctx: MiddlewareContext,
respond: MiddlewareCallback, respond: MiddlewareCallback,
): Promise<void> => { ): Promise<void> => {
if (!this.#parent) { if (!this.#parent) {
return this.#middleware.run(ctx, respond) return this.#middleware.run(ctx, respond);
}
return this.#middleware.enhanceRun(this.#parent.#run)(ctx, respond)
} }
return this.#middleware.enhanceRun(this.#parent.#run)(ctx, respond);
};
} }
for (const method of PLAIN_METHODS) { for (const method of PLAIN_METHODS) {
Axios.prototype[method] = function processRequestMethod(url, config = {}) { Axios.prototype[method] = function processRequestMethod(url, config = {}) {
config.method = method config.method = method;
return this.request(url, config) return this.request(url, config);
} };
} }
for (const method of WITH_PARAMS_METHODS) { for (const method of WITH_PARAMS_METHODS) {
Axios.prototype[method] = function processRequestMethodWithParams( Axios.prototype[method] = function processRequestMethodWithParams(
url, url,
params = {}, params,
config = {}, config = {},
) { ) {
config.method = method config.method = method;
config.params = deepMerge(params, config.params ?? {}) config.params = deepMerge(params, config.params);
return this.request(url, config) return this.request(url, config);
} };
} }
for (const method of WITH_DATA_METHODS) { for (const method of WITH_DATA_METHODS) {
@ -554,8 +554,8 @@ for (const method of WITH_DATA_METHODS) {
data, data,
config = {}, config = {},
) { ) {
config.method = method config.method = method;
config.data = data config.data = data;
return this.request(url, config) return this.request(url, config);
} };
} }

View File

@ -1,9 +1,9 @@
import { assert } from '../helpers/error' import { assert } from '../helpers/error';
import { isFunction } from '../helpers/isTypes' import { isFunction } from '../helpers/isTypes';
import { AxiosRequestConfig, AxiosResponse } from './Axios' import { AxiosRequestConfig, AxiosResponse } from './Axios';
export interface MiddlewareNext { 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 { 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 * @param middleware
*/ */
use(middleware: MiddlewareCallback) { use(middleware: MiddlewareCallback) {
assert(isFunction(middleware), 'middleware 不是一个 function') assert(isFunction(middleware), 'middleware 不是一个 function');
this.#middlewares.push(middleware) this.#middlewares.push(middleware);
} }
/** /**
@ -55,7 +55,7 @@ export default class MiddlewareManager {
return { return {
req: config, req: config,
res: null, res: null,
} };
} }
/** /**
@ -65,11 +65,11 @@ export default class MiddlewareManager {
* @param respond * @param respond
*/ */
run(ctx: MiddlewareContext, respond: MiddlewareCallback) { run(ctx: MiddlewareContext, respond: MiddlewareCallback) {
const middlewares = [...this.#middlewares, respond] const middlewares = [...this.#middlewares, respond];
async function next() { 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'] { enhanceRun(enhancer: MiddlewareManager['run']): MiddlewareManager['run'] {
return (ctx, respond) => { return (ctx, respond) => {
return enhancer(ctx, () => this.run(ctx, respond)) return enhancer(ctx, () => this.run(ctx, respond));
} };
} }
} }

View File

@ -1,15 +1,15 @@
import { AxiosRequestConfig } from '../core/Axios' import { AxiosRequestConfig } from '../core/Axios';
import { isPlainObject } from './isTypes' import { isPlainObject } from './isTypes';
import { buildURL } from './buildURL' import { buildURL } from './buildURL';
import { combineURL } from './combineURL' import { combineURL } from './combineURL';
import { dynamicURL } from './dynamicURL' import { dynamicURL } from './dynamicURL';
export function transformURL(config: AxiosRequestConfig) { export function transformURL(config: AxiosRequestConfig) {
const fullPath = dynamicURL( const fullPath = dynamicURL(
combineURL(config.baseURL, config.url), combineURL(config.baseURL, config.url),
config.params, config.params,
isPlainObject(config.data) ? config.data : {}, isPlainObject(config.data) ? config.data : {},
) );
return buildURL(fullPath, config.params, config.paramsSerializer) return buildURL(fullPath, config.params, config.paramsSerializer);
} }

View File

@ -1,12 +1,12 @@
import { WITH_DATA_RE } from '../constants/methods' import { WITH_DATA_RE } from '../constants/methods';
import { isFunction, isString } from '../helpers/isTypes' import { isFunction, isString } from '../helpers/isTypes';
import { assert } from '../helpers/error' import { assert } from '../helpers/error';
import { AxiosRequestConfig, AxiosResponse } from '../core/Axios' import { AxiosRequestConfig, AxiosResponse } from '../core/Axios';
import { Cancel, isCancel, isCancelToken } from './cancel' import { Cancel, isCancel, isCancelToken } from './cancel';
import { flattenHeaders } from './flattenHeaders' import { flattenHeaders } from './flattenHeaders';
import { AxiosTransformer, transformData } from './transformData' import { AxiosTransformer, transformData } from './transformData';
import { request } from './request' import { request } from './request';
import { AxiosErrorResponse } from './createError' import { AxiosErrorResponse } from './createError';
/** /**
* *
@ -16,51 +16,51 @@ import { AxiosErrorResponse } from './createError'
* @param config * @param config
*/ */
export function dispatchRequest(config: AxiosRequestConfig) { export function dispatchRequest(config: AxiosRequestConfig) {
throwIfCancellationRequested(config) throwIfCancellationRequested(config);
assert(isFunction(config.adapter), 'adapter 不是一个 function') assert(isFunction(config.adapter), 'adapter 不是一个 function');
assert(isString(config.url), 'url 不是一个 string') assert(isString(config.url), 'url 不是一个 string');
assert(isString(config.method), 'method 不是一个 string') assert(isString(config.method), 'method 不是一个 string');
config.headers = flattenHeaders(config) config.headers = flattenHeaders(config);
// 可以携带 data 的请求方法,转换 data // 可以携带 data 的请求方法,转换 data
// 否则,删除 data // 否则,删除 data
if (WITH_DATA_RE.test(config.method!)) { if (WITH_DATA_RE.test(config.method!)) {
dataTransformer(config, config.transformRequest) dataTransformer(config, config.transformRequest);
} else { } else {
delete config.data delete config.data;
} }
function onSuccess(response: AxiosResponse) { function onSuccess(response: AxiosResponse) {
throwIfCancellationRequested(config) throwIfCancellationRequested(config);
dataTransformer(response, config.transformResponse) dataTransformer(response, config.transformResponse);
return response return response;
} }
function onError(error: Cancel | AxiosErrorResponse) { function onError(error: Cancel | AxiosErrorResponse) {
if (!isCancel(error)) { if (!isCancel(error)) {
throwIfCancellationRequested(config) throwIfCancellationRequested(config);
dataTransformer(error.response, config.transformResponse) dataTransformer(error.response, config.transformResponse);
} }
return Promise.reject(error) return Promise.reject(error);
} }
function dataTransformer<TData = unknown>( function dataTransformer<TData = unknown>(
obj: { data?: TData; headers?: AnyObject }, obj: { data?: TData; headers?: AnyObject },
fn?: AxiosTransformer<TData>, 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) { function throwIfCancellationRequested(config: AxiosRequestConfig) {
const { cancelToken } = config const { cancelToken } = config;
if (isCancelToken(cancelToken)) { if (isCancelToken(cancelToken)) {
cancelToken.throwIfRequested() cancelToken.throwIfRequested();
} }
} }

View File

@ -1,20 +1,20 @@
import { isFunction, isPlainObject } from '../helpers/isTypes' import { isFunction, isPlainObject } from '../helpers/isTypes';
import { transformURL } from '../helpers/transformURL' import { transformURL } from '../helpers/transformURL';
import { import {
AxiosRequestConfig, AxiosRequestConfig,
AxiosResponse, AxiosResponse,
AxiosResponseError, AxiosResponseError,
} from '../core/Axios' } from '../core/Axios';
import { import {
AxiosAdapterRequestConfig, AxiosAdapterRequestConfig,
AxiosAdapterResponse, AxiosAdapterResponse,
AxiosAdapterResponseError, AxiosAdapterResponseError,
AxiosAdapterPlatformTask, AxiosAdapterPlatformTask,
AxiosAdapterRequestMethod, AxiosAdapterRequestMethod,
} from '../adpater/createAdapter' } from '../adpater/createAdapter';
import { isCancelToken } from './cancel' import { isCancelToken } from './cancel';
import { AxiosErrorResponse, createError } from './createError' import { AxiosErrorResponse, createError } from './createError';
import { generateType } from './generateType' import { generateType } from './generateType';
/** /**
* *
@ -32,91 +32,91 @@ export function request(config: AxiosRequestConfig) {
method: config.method!.toUpperCase() as AxiosAdapterRequestMethod, method: config.method!.toUpperCase() as AxiosAdapterRequestMethod,
success, success,
fail, fail,
} };
let adapterTask: AxiosAdapterPlatformTask let adapterTask: AxiosAdapterPlatformTask;
try { try {
adapterTask = config.adapter!(adapterConfig) adapterTask = config.adapter!(adapterConfig);
} catch (err) { } catch (err) {
fail({ fail({
status: 400, status: 400,
statusText: 'Bad Adapter', statusText: 'Bad Adapter',
}) });
console.error(err) console.error(err);
} }
function success(baseResponse: AxiosAdapterResponse): void { function success(baseResponse: AxiosAdapterResponse): void {
const response = baseResponse as AxiosResponse const response = baseResponse as AxiosResponse;
response.status = response.status ?? 200 response.status = response.status ?? 200;
response.statusText = response.statusText ?? 'OK' response.statusText = response.statusText ?? 'OK';
response.headers = response.headers ?? {} response.headers = response.headers ?? {};
response.config = config response.config = config;
response.request = adapterTask response.request = adapterTask;
const { validateStatus } = config const { validateStatus } = config;
if (!isFunction(validateStatus) || validateStatus(response.status)) { if (!isFunction(validateStatus) || validateStatus(response.status)) {
resolve(response) resolve(response);
} else { } else {
catchError('validate status error', response) catchError('validate status error', response);
} }
} }
function fail(baseResponseError: AxiosAdapterResponseError): void { function fail(baseResponseError: AxiosAdapterResponseError): void {
const responseError = baseResponseError as AxiosResponseError const responseError = baseResponseError as AxiosResponseError;
responseError.isFail = true responseError.isFail = true;
responseError.status = responseError.status ?? 400 responseError.status = responseError.status ?? 400;
responseError.statusText = responseError.statusText ?? 'Fail' responseError.statusText = responseError.statusText ?? 'Fail';
responseError.headers = responseError.headers ?? {} responseError.headers = responseError.headers ?? {};
responseError.config = config responseError.config = config;
responseError.request = adapterTask responseError.request = adapterTask;
catchError('request fail', responseError) catchError('request fail', responseError);
} }
function catchError( function catchError(
message: string, message: string,
errorResponse: AxiosErrorResponse, errorResponse: AxiosErrorResponse,
): void { ): void {
reject(createError(message, config, errorResponse, adapterTask)) reject(createError(message, config, errorResponse, adapterTask));
} }
if (isPlainObject(adapterTask)) { if (isPlainObject(adapterTask)) {
tryToggleProgressUpdate(adapterConfig, adapterTask.onProgressUpdate) tryToggleProgressUpdate(adapterConfig, adapterTask.onProgressUpdate);
} }
const { cancelToken } = config const { cancelToken } = config;
if (isCancelToken(cancelToken)) { if (isCancelToken(cancelToken)) {
cancelToken.onCancel((reason) => { cancelToken.onCancel((reason) => {
if (isPlainObject(adapterTask)) { if (isPlainObject(adapterTask)) {
tryToggleProgressUpdate(adapterConfig, adapterTask.offProgressUpdate) tryToggleProgressUpdate(adapterConfig, adapterTask.offProgressUpdate);
adapterTask?.abort?.() adapterTask?.abort?.();
} }
reject(reason) reject(reason);
}) });
} }
}) });
} }
function tryToggleProgressUpdate( function tryToggleProgressUpdate(
config: AxiosAdapterRequestConfig, config: AxiosAdapterRequestConfig,
progress?: (cb: (event: AnyObject) => void) => void, progress?: (cb: (event: AnyObject) => void) => void,
) { ) {
const { type, onUploadProgress, onDownloadProgress } = config const { type, onUploadProgress, onDownloadProgress } = config;
if (isFunction(progress)) { if (isFunction(progress)) {
switch (type) { switch (type) {
case 'upload': case 'upload':
if (isFunction(onUploadProgress)) { if (isFunction(onUploadProgress)) {
progress(onUploadProgress) progress(onUploadProgress);
} }
break break;
case 'download': case 'download':
if (isFunction(onDownloadProgress)) { if (isFunction(onDownloadProgress)) {
progress(onDownloadProgress) progress(onDownloadProgress);
} }
break break;
} }
} }
} }

View File

@ -1 +1 @@
export const version = '2.4.1' export const version = '2.4.1';

View File

@ -1,14 +1,14 @@
import { describe, test, expect, vi } from 'vitest' import { describe, test, expect, vi } from 'vitest';
import { asyncNext, mockAdapter } from 'scripts/test.utils' import { asyncNext, mockAdapter } from 'scripts/test.utils';
import { import {
PLAIN_METHODS, PLAIN_METHODS,
WITH_DATA_METHODS, WITH_DATA_METHODS,
WITH_PARAMS_METHODS, WITH_PARAMS_METHODS,
} from '@/constants/methods' } from '@/constants/methods';
import { dispatchRequest } from '@/request/dispatchRequest' import { dispatchRequest } from '@/request/dispatchRequest';
import axios from '@/axios' import axios from '@/axios';
import _defaults from '@/defaults' import _defaults from '@/defaults';
describe('src/request/dispatchRequest.ts', () => { describe('src/request/dispatchRequest.ts', () => {
const defaults = { const defaults = {
@ -17,32 +17,32 @@ describe('src/request/dispatchRequest.ts', () => {
baseURL: 'http://api.com', baseURL: 'http://api.com',
method: 'get' as const, method: 'get' as const,
headers: {}, headers: {},
} };
test('应该抛出异常', () => { test('应该抛出异常', () => {
expect(() => dispatchRequest({})).toThrowErrorMatchingInlineSnapshot( expect(() => dispatchRequest({})).toThrowErrorMatchingInlineSnapshot(
'"[axios-miniprogram]: adapter 不是一个 function"', '"[axios-miniprogram]: adapter 不是一个 function"',
) );
expect(() => expect(() =>
dispatchRequest({ adapter: mockAdapter() }), dispatchRequest({ adapter: mockAdapter() }),
).toThrowErrorMatchingInlineSnapshot( ).toThrowErrorMatchingInlineSnapshot(
'"[axios-miniprogram]: url 不是一个 string"', '"[axios-miniprogram]: url 不是一个 string"',
) );
expect(() => expect(() =>
dispatchRequest({ adapter: mockAdapter(), url: '/' }), dispatchRequest({ adapter: mockAdapter(), url: '/' }),
).toThrowErrorMatchingInlineSnapshot( ).toThrowErrorMatchingInlineSnapshot(
'"[axios-miniprogram]: method 不是一个 string"', '"[axios-miniprogram]: method 不是一个 string"',
) );
expect(() => expect(() =>
dispatchRequest({ adapter: mockAdapter(), url: '/', method: 'get' }), dispatchRequest({ adapter: mockAdapter(), url: '/', method: 'get' }),
).not.toThrowError() ).not.toThrowError();
}) });
test('坏的适配器应该抛出异常', () => { test('坏的适配器应该抛出异常', () => {
expect( expect(
dispatchRequest({ dispatchRequest({
adapter: () => { adapter: () => {
throw 'bad adapter' throw 'bad adapter';
}, },
url: '/', url: '/',
method: 'get', method: 'get',
@ -71,8 +71,8 @@ describe('src/request/dispatchRequest.ts', () => {
"statusText": "Bad Adapter", "statusText": "Bad Adapter",
}, },
} }
`) `);
}) });
test('应该支持拉平请求头', () => { test('应该支持拉平请求头', () => {
const c = { const c = {
@ -87,16 +87,16 @@ describe('src/request/dispatchRequest.ts', () => {
}, },
h3: 3, h3: 3,
}, },
} };
dispatchRequest(c) dispatchRequest(c);
expect(c.headers).toEqual({ expect(c.headers).toEqual({
h1: 1, h1: 1,
h2: 2, h2: 2,
h3: 3, h3: 3,
}) });
}) });
test.each(WITH_DATA_METHODS)('%s 方法应该支持转换请求数据', (k) => { test.each(WITH_DATA_METHODS)('%s 方法应该支持转换请求数据', (k) => {
const c = { const c = {
@ -105,12 +105,12 @@ describe('src/request/dispatchRequest.ts', () => {
method: k, method: k,
data: {}, data: {},
transformRequest: () => ({ id: 1 }), transformRequest: () => ({ id: 1 }),
} };
dispatchRequest(c) dispatchRequest(c);
expect(c.data).toEqual({ id: 1 }) expect(c.data).toEqual({ id: 1 });
}) });
test('不能带数据的请求方法应该删除数据', () => { test('不能带数据的请求方法应该删除数据', () => {
const c = { const c = {
@ -118,66 +118,66 @@ describe('src/request/dispatchRequest.ts', () => {
url: 'test', url: 'test',
data: {}, data: {},
transformRequest: () => ({ id: 1 }), transformRequest: () => ({ id: 1 }),
} };
;[...PLAIN_METHODS, ...WITH_PARAMS_METHODS].forEach((k) => { [...PLAIN_METHODS, ...WITH_PARAMS_METHODS].forEach((k) => {
const s = { ...c, method: k } const s = { ...c, method: k };
dispatchRequest(s) dispatchRequest(s);
expect(s.data).toBeUndefined() expect(s.data).toBeUndefined();
}) });
}) });
test('应该支持转换响应数据', async () => { test('应该支持转换响应数据', async () => {
const c = { const c = {
...defaults, ...defaults,
url: 'test', url: 'test',
transformResponse: () => ({ result: 1 }), 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 () => { test('请求发送前取消请求应该抛出异常', async () => {
const cb = vi.fn() const cb = vi.fn();
const { cancel, token } = axios.CancelToken.source() const { cancel, token } = axios.CancelToken.source();
const c = { const c = {
...defaults, ...defaults,
url: 'test', url: 'test',
cancelToken: token, cancelToken: token,
} };
cancel() cancel();
try { try {
dispatchRequest(c) dispatchRequest(c);
} catch (err) { } catch (err) {
cb(err) cb(err);
} }
expect(cb).toBeCalled() expect(cb).toBeCalled();
expect(axios.isCancel(cb.mock.calls[0][0])).toBeTruthy() expect(axios.isCancel(cb.mock.calls[0][0])).toBeTruthy();
}) });
test('请求发送后取消请求应该抛出异常', async () => { test('请求发送后取消请求应该抛出异常', async () => {
const cb = vi.fn() const cb = vi.fn();
const { cancel, token } = axios.CancelToken.source() const { cancel, token } = axios.CancelToken.source();
const c = { const c = {
...defaults, ...defaults,
url: 'test', url: 'test',
cancelToken: token, cancelToken: token,
} };
const p = dispatchRequest(c).catch(cb) const p = dispatchRequest(c).catch(cb);
await asyncNext() await asyncNext();
expect(cb).not.toBeCalled() expect(cb).not.toBeCalled();
cancel() cancel();
await p await p;
expect(cb).toBeCalled() expect(cb).toBeCalled();
expect(axios.isCancel(cb.mock.calls[0][0])).toBeTruthy() expect(axios.isCancel(cb.mock.calls[0][0])).toBeTruthy();
}) });
}) });