Compare commits

..

No commits in common. "main" and "v2.2.0" have entirely different histories.
main ... v2.2.0

156 changed files with 5207 additions and 22058 deletions

View File

@ -1,52 +1,50 @@
const { execSync } = require('child_process')
const { execSync } = require('child_process');
const metas = [
{ type: 'feat', section: '✨ Features | 新功能' },
{ type: 'fix', section: '🐛 Bug Fixes | Bug 修复' },
{ type: 'test', section: '✅ Tests | 测试' },
{ type: 'docs', section: '📝 Documentation | 文档' },
{ type: 'build', section: '👷‍ Build System | 构建' },
{ type: 'ci', section: '🔧 Continuous Integration | CI 配置' },
{ type: 'perf', section: '⚡ Performance Improvements | 性能优化' },
{ type: 'revert', section: '⏪ Reverts | 回退' },
{ type: 'chore', section: '📦 Chores | 其他更新' },
{ type: 'style', section: '💄 Styles | 风格', hidden: true },
{ type: 'refactor', section: '♻ Code Refactoring | 代码重构' },
]
{ type: 'feat', section: '✨ Features | 新功能' },
{ type: 'fix', section: '🐛 Bug Fixes | Bug 修复' },
{ type: 'test', section: '✅ Tests | 测试' },
{ type: 'docs', section: '📝 Documentation | 文档' },
{ type: 'build', section: '👷‍ Build System | 构建' },
{ type: 'ci', section: '🔧 Continuous Integration | CI 配置' },
{ type: 'perf', section: '⚡ Performance Improvements | 性能优化' },
{ type: 'revert', section: '⏪ Reverts | 回退' },
{ type: 'chore', section: '📦 Chores | 其他更新' },
{ type: 'style', section: '💄 Styles | 风格', hidden: true },
{ type: 'refactor', section: '♻ Code Refactoring | 代码重构' },
];
/** @type {import('cz-git').UserConfig} */
module.exports = {
rules: {
// @see: https://commitlint.js.org/#/reference-rules
'subject-min-length': [0, 'always', 3],
'subject-max-length': [0, 'always', 80],
'type-enum': [0, 'always', metas.map((meta) => meta.type)],
},
prompt: {
messages: {
type: '请选择提交类型',
subject: '请输入变更描述',
breaking: '列举非兼容性重大的变更,如果有多行,使用 "|" 换行(选填项)\n',
footer: '列举关联的 issue例如#31,#I3244选填项\n',
confirmCommit: '确定提交',
},
types: metas.map((meta) => ({
value: meta.type,
name: `${`${meta.type}:`.padEnd(10, ' ')}${meta.section}`,
})),
allowBreakingChanges: ['feat', 'fix'],
skipQuestions: ['scope', 'body', 'footerPrefix'],
formatMessageCB: (commit) =>
`${commit?.defaultMessage}\n\nCo-authored-by: ${readGitUser(
'name',
)} <${readGitUser('email')}>`,
},
}
rules: {
// @see: https://commitlint.js.org/#/reference-rules
'subject-min-length': [0, 'always', 3],
'subject-max-length': [0, 'always', 80],
'type-enum': [0, 'always', metas.map((meta) => meta.type)],
},
prompt: {
messages: {
type: '请选择提交类型',
subject: '请输入变更描述',
breaking: '列举非兼容性重大的变更,如果有多行,使用 "|" 换行(选填项)\n',
footer: '列举关联的 issue例如#31,#I3244选填项\n',
confirmCommit: '确定提交',
},
types: metas.map((meta) => ({
value: meta.type,
name: `${`${meta.type}:`.padEnd(10, ' ')}${meta.section}`,
})),
allowBreakingChanges: ['feat', 'fix'],
skipQuestions: ['scope', 'body', 'footerPrefix'],
formatMessageCB: (commit) =>
`${commit?.defaultMessage}\n\nCo-authored-by: ${readGitUser(
'name',
)} <${readGitUser('email')}>`,
},
};
function readGitUser(key) {
return execSync(`git config user.${key}`, {
stdio: 'pipe',
})
.toString()
.replace(/(\r\n\t|\n|\r\t)/g, '')
return execSync(`git config user.${key}`)
.toString()
.replace(/(\r\n\t|\n|\r\t)/g, '');
}

View File

@ -1,4 +1 @@
dist/
example/dist/
example/config/**.js
/dist

View File

@ -1,16 +0,0 @@
{
"root": true,
"env": {
"es2022": true,
"node": true
},
"extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended"],
"parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint"],
"rules": {
"@typescript-eslint/no-explicit-any": 0,
"@typescript-eslint/no-non-null-assertion": 0,
"@typescript-eslint/ban-ts-comment": 0,
"no-mixed-spaces-and-tabs": 0
}
}

14
.eslintrc.json Normal file
View File

@ -0,0 +1,14 @@
{
"env": {
"es2022": true,
"node": true
},
"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
}
}

View File

@ -37,13 +37,13 @@ body:
label: 验证
description: 在提交问题之前,请确保您执行以下操作
options:
- label: 遵守我们的[行为准则 ](https://github.com/zjxxxxxxxxx/axios-miniprogram/blob/main/CODE_OF_CONDUCT.md)
- label: 遵守我们的[行为准则 ](https://github.com/zjx0905/axios-miniprogram/blob/main/CODE_OF_CONDUCT.md)
required: true
- label: 阅读[贡献指南](https://github.com/zjxxxxxxxxx/axios-miniprogram/blob/main/CONTRIBUTING.md).
- label: 阅读[贡献指南](https://github.com/zjx0905/axios-miniprogram/blob/main/CONTRIBUTING.md).
required: true
- label: 阅读[文档](https://axios-miniprogram.com).
required: true
- label: 检查是否还没有报告相同错误的[问题](https://github.com/zjxxxxxxxxx/axios-miniprogram/issues)以避免创建重复。
- label: 检查是否还没有报告相同错误的[问题](https://github.com/zjx0905/axios-miniprogram/issues)以避免创建重复。
required: true
- label: 确保这是 axios-miniprogram 问题而不是特定于框架的问题。
required: true

View File

@ -17,7 +17,7 @@ body:
id: suggested-solution
attributes:
label: 建议的解决方案
description: '我们可以提供以下实现......'
description: '在模块 [xy] 中,我们可以提供以下实现......'
validations:
required: true
- type: textarea
@ -36,9 +36,9 @@ body:
label: 验证
description: 在提交问题之前,请确保您执行以下操作
options:
- label: 遵守我们的[行为准则 ](https://github.com/zjxxxxxxxxx/axios-miniprogram/blob/main/CODE_OF_CONDUCT.md)
- label: 遵守我们的[行为准则 ](https://github.com/zjx0905/axios-miniprogram/blob/main/CODE_OF_CONDUCT.md)
required: true
- label: 阅读[贡献指南](https://github.com/zjxxxxxxxxx/axios-miniprogram/blob/main/CONTRIBUTING.md).
- label: 阅读[贡献指南](https://github.com/zjx0905/axios-miniprogram/blob/main/CONTRIBUTING.md).
required: true
- label: 阅读[文档](https://axios-miniprogram.com).
required: true

View File

@ -24,7 +24,7 @@ jobs:
- name: Install pnpm
uses: pnpm/action-setup@v2
with:
version: 8
version: 7
- name: Set node
uses: actions/setup-node@v3
@ -33,18 +33,18 @@ jobs:
cache: pnpm
- name: Install
run: pnpm install --no-frozen-lockfile
run: pnpm i
- name: Lint
run: pnpm lint
- name: Build all
- name: Build
run: pnpm build -a
- name: Build assets
run: pnpm build:assets
- name: Build asset
run: pnpm build:asset
- name: Typecheck
- name: Test
run: pnpm typecheck
- name: Test

View File

@ -2,10 +2,17 @@ name: Deploy Docs
on:
push:
tags:
- v*
branches:
- docs
- main
paths:
- 'docs/**'
- '**.md'
pull_request:
branches:
- main
paths:
- 'docs/**'
- '**.md'
workflow_dispatch:
jobs:
@ -18,7 +25,7 @@ jobs:
- name: Install pnpm
uses: pnpm/action-setup@v2
with:
version: 8
version: 7
- name: Set node
uses: actions/setup-node@v3
@ -27,7 +34,7 @@ jobs:
cache: pnpm
- name: Install
run: pnpm install --no-frozen-lockfile
run: pnpm i
- name: Build
run: pnpm docs:build

View File

@ -15,7 +15,7 @@ jobs:
- name: Install pnpm
uses: pnpm/action-setup@v2
with:
version: 8
version: 7
- name: Set node
uses: actions/setup-node@v3
@ -24,7 +24,7 @@ jobs:
cache: pnpm
- name: Install
run: pnpm install --no-frozen-lockfile
run: pnpm i
- name: Build
run: pnpm build -a

View File

@ -15,7 +15,7 @@ jobs:
- name: Install pnpm
uses: pnpm/action-setup@v2
with:
version: 8
version: 7
- name: Set node
uses: actions/setup-node@v3
@ -24,10 +24,7 @@ jobs:
cache: pnpm
- name: Install
run: pnpm install --no-frozen-lockfile
- name: Build Release Assets
run: pnpm build:assets
run: pnpm i
- name: Create releaselog
run: pnpm releaselog
@ -39,12 +36,22 @@ jobs:
script: return /-/.test("${{ github.ref }}")
- name: Create Release
uses: softprops/action-gh-release@v1
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ github.ref }}
name: Release ${{ github.ref_name }}
prerelease: ${{ steps.prerelease.outputs.result }}
release_name: Release ${{ github.ref }}
body_path: 'RELEASELOG.md'
files: 'dist/**.zip'
prerelease: ${{ steps.prerelease.outputs.result }}
- name: Build Release Asset
run: pnpm build:asset
- name: Upload Release Asset
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
RELEASE_ID: ${{ steps.create_release.outputs.id }}
UPLOAD_URL: ${{ steps.create_release.outputs.upload_url }}
run: pnpm upload:asset

4
.gitignore vendored
View File

@ -3,6 +3,7 @@ node_modules
*.log
# Docs
dist
docs/.vitepress/cache
docs/pages/guide/intro.md
@ -10,8 +11,7 @@ docs/pages/guide/intro.md
.DS_Store
# Bundle
dist/
.swc
lib/
# Typescript build file
*.tsbuildinfo

View File

@ -1,5 +1 @@
CHANGELOG.md
dist/
example/dist/
example/config/**.js

View File

@ -1,219 +1,49 @@
## [2.7.2](https://github.com/zjxxxxxxxxx/axios-miniprogram/compare/v2.7.1...v2.7.2) (2024-01-31)
# [2.2.0](https://github.com/zjx0905/axios-miniprogram/compare/v2.1.0...v2.2.0) (2023-04-16)
### Bug Fixes
* 修复设置请求 headers 影响了全局配置 ([#56](https://github.com/zjxxxxxxxxx/axios-miniprogram/issues/56)) ([5d45cd9](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/5d45cd9670c3bc8b58437d2defc58753ebc6392e)), closes [#55](https://github.com/zjxxxxxxxxx/axios-miniprogram/issues/55)
* 修复 Proxy uni 错误 ([021e052](https://github.com/zjx0905/axios-miniprogram/commit/021e05233a95ebc5c5f93d114d225cc45a22675f))
### Features
* 仅 post/put/patch 方法允许设置请求数据 ([2c3ff56](https://github.com/zjx0905/axios-miniprogram/commit/2c3ff567c19197f6377645cd9f7109806cd93b77))
* 支持 HTTP PATCH 请求 ([22bcefc](https://github.com/zjx0905/axios-miniprogram/commit/22bcefcb97e50400403b131d307c97eb4cbb6071))
## [2.7.1](https://github.com/zjxxxxxxxxx/axios-miniprogram/compare/v2.7.0...v2.7.1) (2023-12-16)
# [2.1.0](https://github.com/zjx0905/axios-miniprogram/compare/v2.0.0...v2.1.0) (2023-04-11)
### Bug Fixes
* 对上传文件响应数据JSON.parse ([#54](https://github.com/zjxxxxxxxxx/axios-miniprogram/issues/54)) ([df42674](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/df4267489508f6d1851f52d78e9d9179709a562a)), closes [#53](https://github.com/zjxxxxxxxxx/axios-miniprogram/issues/53)
* 修复 axios.fork() 无法访问私有方法 ([2254e73](https://github.com/zjx0905/axios-miniprogram/commit/2254e73cf76f1bc95d4850211e3fa34acae50136))
* 移除 url 末尾的斜线 ([1c09ffd](https://github.com/zjx0905/axios-miniprogram/commit/1c09ffdd91d554078423cba57fe036106e9b0fa8))
### Features
* 添加符合 HTTP 规范的 statusText ([#49](https://github.com/zjxxxxxxxxx/axios-miniprogram/issues/49)) ([3848fdd](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/3848fdd81bf8fb1f5e373ca4e117adb653969acf))
* 适配器异常处理成响应异常 ([be17ba7](https://github.com/zjx0905/axios-miniprogram/commit/be17ba7e6881699aeb74b45c8b4b084e1e53a777))
* 添加新功能 派生领域 axios.fork() ([222b935](https://github.com/zjx0905/axios-miniprogram/commit/222b935f6839ce8fcecfa951d937e6160211f7f9))
* 修改 mergeConfig 中 data 的合并方式 ([ee6a31b](https://github.com/zjx0905/axios-miniprogram/commit/ee6a31b4bbc07e93f8754c83a1ff02495a23dfa7))
* 支持深度合并 params & data ([22f65cf](https://github.com/zjx0905/axios-miniprogram/commit/22f65cf69c877f314b269d8c3d0fac8f1c8ab71f))
* fileName 替换为 name ([69044f3](https://github.com/zjx0905/axios-miniprogram/commit/69044f35833d8d42a5f0c12b01687298c08f589b))
# [2.7.0](https://github.com/zjxxxxxxxxx/axios-miniprogram/compare/v2.6.0...v2.7.0) (2023-08-17)
# [2.0.0](https://github.com/zjx0905/axios-miniprogram/compare/v2.0.0-beta.10...v2.0.0) (2023-04-05)
### Bug Fixes
* 修复 errno 和 errMsg 丢失 ([71e3007](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/71e30073890974f54461134620dfbda58cc36af0))
* 修复 dynamicURL 错误匹配端口号 ([7e29e91](https://github.com/zjx0905/axios-miniprogram/commit/7e29e91f0a2a4b1b1f3ca49a9cd5ff123466301a))
### Features
* 新增支持小红书小程序 ([53f0432](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/53f043275ced79c7204d791c62721e36db512f24))
# [2.6.0](https://github.com/zjxxxxxxxxx/axios-miniprogram/compare/v2.5.0...v2.6.0) (2023-08-13)
### Features
* 废弃 fork API ([a04f833](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/a04f833d917cb07c3bd95678260971194179def0))
### BREAKING CHANGES
* axios.fork() 已废弃
# [2.5.0](https://github.com/zjxxxxxxxxx/axios-miniprogram/compare/v2.4.2...v2.5.0) (2023-06-04)
### Features
* 移除内置的 uni 适配器 ([96ea026](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/96ea0266dd7c0da26341d8fea4d3bdb53361ffd0)), closes [#40](https://github.com/zjxxxxxxxxx/axios-miniprogram/issues/40)
### BREAKING CHANGES
* uni 不再内部支持, 可以参阅文档中的自定义适配器自行适配 uni
## [2.4.2](https://github.com/zjxxxxxxxxx/axios-miniprogram/compare/v2.4.1...v2.4.2) (2023-05-14)
### Bug Fixes
* axios.use 函数返回值不是当前实例 ([74856f7](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/74856f7fdef4f0e75b8665300960416a840f561c))
### Features
* 发出请求前进行动态地址插值 ([b6698ca](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/b6698ca22da3f754e21916e69d43b961e12571e6))
## [2.4.1](https://github.com/zjxxxxxxxxx/axios-miniprogram/compare/v2.4.0...v2.4.1) (2023-05-04)
### Bug Fixes
* 配置原始 URL 丢失 ([8b6eed2](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/8b6eed2d6df5c7aacd181f6fbcfba9eca875178c))
* 配置原始请求方法丢失 ([c107171](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/c107171eba69a129eddad34861611837a0efac25))
### Features
* 请求发送前请求方法转小写 ([0b82403](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/0b82403c4c630676042ff390b77d5791c4ab0a6e))
* 允许设置默认请求方法 ([4b02582](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/4b025821525712d7e6bb68faa9af3cf7d9ad0e0d))
* getUri 支持 baseURL/dynamicURL ([633c920](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/633c92024718370e24919fcfb44b86b795248c8f))
### Performance Improvements
* 优化中间件 ([3931f23](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/3931f230deffbb72a70fd24798334e63a3d531f9))
# [2.4.0](https://github.com/zjxxxxxxxxx/axios-miniprogram/compare/v2.3.2...v2.4.0) (2023-04-25)
### Bug Fixes
* 丢失末尾自带的斜线 ([db787a2](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/db787a2b5f7f1188d1813ddb715ef23e653120a9)), closes [#44](https://github.com/zjxxxxxxxxx/axios-miniprogram/issues/44)
### Features
* 全局方法 create 改为实例方法 ([a84533a](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/a84533a09f493e27ba3e567549be5e534271ed22))
* 添加扩展实例 ([9093e1b](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/9093e1bdffe5bd75fccfeeeeb0e2b487751c549a))
* 添加中间件 ([6263759](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/6263759ba94b2269082c49a2f2a5e038f6766027))
* 支持复用父级中间件 ([bfc012b](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/bfc012b4999d717629b997ab908fd411954b0323))
### Reverts
* 取消支持为路径添加中间件 ([1e5809a](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/1e5809aee3f1653eced0c2ca351c6e3f8616f719))
### BREAKING CHANGES
* 原派生领域替换为功能更强的扩展实例
## [2.3.2](https://github.com/zjxxxxxxxxx/axios-miniprogram/compare/v2.3.1...v2.3.2) (2023-04-23)
### Bug Fixes
* 适配器请求头丢失 ([c0ca900](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/c0ca9001d2dc2b138a916c18da000b733d58ec7a)), closes [#43](https://github.com/zjxxxxxxxxx/axios-miniprogram/issues/43)
## [2.3.1](https://github.com/zjxxxxxxxxx/axios-miniprogram/compare/v2.3.0...v2.3.1) (2023-04-21)
### Bug Fixes
* 控制台没有输出适配器错误 ([258954a](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/258954afc1c39483ff6b1828c8904c5b284890d2))
* 下载进度/上传进度 类型错误 ([2d691b6](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/2d691b69cbb2d3e27be3698bf4a4188cf71ccb7e))
### Features
* 添加版本号 ([e3346a8](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/e3346a866f12ed8aa07695f45a8177d631973abd))
# [2.3.0](https://github.com/zjxxxxxxxxx/axios-miniprogram/compare/v2.2.0...v2.3.0) (2023-04-18)
### Bug Fixes
* 错误处理不是每次出错都执行 ([fb4762d](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/fb4762d01a0d304ce6c291d6487dce1507a985c5))
* data 不支持对象以外的类型 ([4d8ec80](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/4d8ec80f29b85e3419d1bc5112886a397ee2cc48))
### Features
* 从参数中删除动态地址属性 ([b0eaa04](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/b0eaa04c66dc82de944769893f62ecd0c4ae76d8))
* 提供更多可使用的类型 ([0dc58a4](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/0dc58a4b0cdd5d36c1b16f13697d8180952cb093))
* 支持具名导入工具函数 ([d714ed2](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/d714ed23c0f3b8ea3abecfb042c67bcf9adb29a7))
* 支持清空拦截器 ([cbcc43a](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/cbcc43ad77f0e79223e524aa6bb4502ee4b989c9))
# [2.2.0](https://github.com/zjxxxxxxxxx/axios-miniprogram/compare/v2.1.0...v2.2.0) (2023-04-16)
### Bug Fixes
* 修复 Proxy uni 错误 ([021e052](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/021e05233a95ebc5c5f93d114d225cc45a22675f))
### Features
* 仅 post/put/patch 方法允许设置请求数据 ([2c3ff56](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/2c3ff567c19197f6377645cd9f7109806cd93b77))
* 支持 HTTP PATCH 请求 ([22bcefc](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/22bcefcb97e50400403b131d307c97eb4cbb6071))
# [2.1.0](https://github.com/zjxxxxxxxxx/axios-miniprogram/compare/v2.0.0...v2.1.0) (2023-04-11)
### Bug Fixes
* 修复 axios.fork() 无法访问私有方法 ([2254e73](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/2254e73cf76f1bc95d4850211e3fa34acae50136))
* 移除 url 末尾的斜线 ([1c09ffd](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/1c09ffdd91d554078423cba57fe036106e9b0fa8))
### Features
* 适配器异常处理成响应异常 ([be17ba7](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/be17ba7e6881699aeb74b45c8b4b084e1e53a777))
* 添加新功能 派生领域 axios.fork() ([222b935](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/222b935f6839ce8fcecfa951d937e6160211f7f9))
* 修改 mergeConfig 中 data 的合并方式 ([ee6a31b](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/ee6a31b4bbc07e93f8754c83a1ff02495a23dfa7))
* 支持深度合并 params & data ([22f65cf](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/22f65cf69c877f314b269d8c3d0fac8f1c8ab71f))
* fileName 替换为 name ([69044f3](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/69044f35833d8d42a5f0c12b01687298c08f589b))
# [2.0.0](https://github.com/zjxxxxxxxxx/axios-miniprogram/compare/v2.0.0-beta.10...v2.0.0) (2023-04-05)
### Bug Fixes
* 修复 dynamicURL 错误匹配端口号 ([7e29e91](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/7e29e91f0a2a4b1b1f3ca49a9cd5ff123466301a))
### Features
* 添加新的 API isAxiosError ([61337a9](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/61337a9bbe100cdab9e175f8ee42e4d5d2ba6842))
* 优化 defaults ([2793dd8](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/2793dd8b5e1ad34218088718314e06545033cbbf))
* 添加新的 API isAxiosError ([61337a9](https://github.com/zjx0905/axios-miniprogram/commit/61337a9bbe100cdab9e175f8ee42e4d5d2ba6842))
* 优化 defaults ([2793dd8](https://github.com/zjx0905/axios-miniprogram/commit/2793dd8b5e1ad34218088718314e06545033cbbf))
### BREAKING CHANGES
@ -222,12 +52,12 @@
# [2.0.0-beta.10](https://github.com/zjxxxxxxxxx/axios-miniprogram/compare/v2.0.0-beta.0...v2.0.0-beta.10) (2023-04-05)
# [2.0.0-beta.10](https://github.com/zjx0905/axios-miniprogram/compare/v2.0.0-beta.0...v2.0.0-beta.10) (2023-04-05)
### Features
* 支持 es2015 ([b66176f](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/b66176f0ed90eaec5c1377077359a234691ae1b3))
* 支持 es2015 ([b66176f](https://github.com/zjx0905/axios-miniprogram/commit/b66176f0ed90eaec5c1377077359a234691ae1b3))
@ -235,14 +65,14 @@
### Bug Fixes
* 清理 url 前面多余的斜线 ([666a942](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/666a9427d3c9bfbd96def9e112d5183acdf08d84))
* 清理 url 前面多余的斜线 ([666a942](https://github.com/zjx0905/axios-miniprogram/commit/666a9427d3c9bfbd96def9e112d5183acdf08d84))
### Features
* 增强默认参数系列化器 ([0cfb3e1](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/0cfb3e1ff04b69896ba43ffcb6abba5fb61ad48a))
* 支持合并自定义配置 ([4409a57](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/4409a5720ba1e58a4c218ee67f71d5f05beee6a8)), closes [#38](https://github.com/zjxxxxxxxxx/axios-miniprogram/issues/38)
* 支持京东小程序 ([0d1d21f](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/0d1d21fc66eb202463ef2baaa174b0f60276035e))
* 支持自定义配置 ([b15b31e](https://github.com/zjxxxxxxxxx/axios-miniprogram/commit/b15b31ee55217f11e08713ce02dd7ab21732fba1))
* 增强默认参数系列化器 ([0cfb3e1](https://github.com/zjx0905/axios-miniprogram/commit/0cfb3e1ff04b69896ba43ffcb6abba5fb61ad48a))
* 支持合并自定义配置 ([4409a57](https://github.com/zjx0905/axios-miniprogram/commit/4409a5720ba1e58a4c218ee67f71d5f05beee6a8)), closes [#38](https://github.com/zjx0905/axios-miniprogram/issues/38)
* 支持京东小程序 ([0d1d21f](https://github.com/zjx0905/axios-miniprogram/commit/0d1d21fc66eb202463ef2baaa174b0f60276035e))
* 支持自定义配置 ([b15b31e](https://github.com/zjx0905/axios-miniprogram/commit/b15b31ee55217f11e08713ce02dd7ab21732fba1))
### BREAKING CHANGES

View File

@ -34,7 +34,7 @@ pnpm cz
脚本列表
- `pnpm build` 打包源代码
- `pnpm dev` 监听文件变更并运行 `build`
- `pnpm watch` 监听文件变更并运行 `build`
- `pnpm test` 单元测试
- `pnpm test:watch` 监听文件变更并运行 `test`
- `pnpm test:cov` 运行 `test` 并输出测试覆盖率
@ -50,7 +50,7 @@ pnpm cz
添加新功能有一些注意事项。
- 在你开始工作之前,最好先开一个 [issue](https://github.com/zjxxxxxxxxx/axios-miniprogram/issues) 来讨论。
- 在你开始工作之前,最好先开一个 [issue](https://github.com/zjx0905/axios-miniprogram/issues) 来讨论。
- 应该对新功能进行单元测试。
- 应该在文档中添加相关的使用介绍及方法。

View File

@ -1,6 +1,6 @@
The MIT License (MIT)
Copyright (c) 2020-present, zjxxxxxxxxx <https://github.com/zjxxxxxxxxx>
Copyright (c) 2020-present, zjx0905 <https://github.com/zjx0905>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View File

@ -1,26 +1,24 @@
<h1 align="center">axios-miniprogram</h1>
# axios-miniprogram
<p style="text-align: center;" align="center">
<a style="display: inline-block;margin-left: 5px;" href="https://github.com/zjxxxxxxxxx/axios-miniprogram/actions/workflows/ci.yml">
<img src="https://github.com/zjxxxxxxxxx/axios-miniprogram/actions/workflows/ci.yml/badge.svg" alt="ci"/>
<p style="display: flex;margin-left:-5px;">
<a href="https://github.com/zjx0905/axios-miniprogram/actions/workflows/ci.yml">
<img src="https://github.com/zjx0905/axios-miniprogram/actions/workflows/ci.yml/badge.svg" alt="ci">
</a>
<a style="display: inline-block;margin-left: 5px;" href="https://codecov.io/gh/zjxxxxxxxxx/axios-miniprogram" >
<img src="https://codecov.io/gh/zjxxxxxxxxx/axios-miniprogram/branch/main/graph/badge.svg?token=WIQVYX2WIK" alt="codecov"/>
<a style="margin-left:5px;" href="https://www.npmjs.org/package/axios-miniprogram">
<img src="https://img.shields.io/npm/v/axios-miniprogram" alt="npm">
</a>
<a style="display: inline-block;margin-left: 5px;" href="https://opensource.org/licenses/MIT">
<img src="https://img.shields.io/github/license/zjxxxxxxxxx/axios-miniprogram" alt="license"/>
<a style="margin-left:5px;" href="https://codecov.io/gh/zjx0905/axios-miniprogram" >
<img src="https://codecov.io/gh/zjx0905/axios-miniprogram/branch/main/graph/badge.svg?token=WIQVYX2WIK" alt="codecov"/>
</a>
<a style="display: inline-block;margin-left: 5px;" href="https://www.npmjs.org/package/axios-miniprogram">
<img src="https://img.shields.io/bundlephobia/min/axios-miniprogram" alt="npm bundle size"/>
</a>
<a style="display: inline-block;" href="https://www.npmjs.org/package/axios-miniprogram">
<img alt="npm" src="https://img.shields.io/npm/dt/axios-miniprogram"/>
<a style="margin-left:5px;" href="https://www.npmjs.org/package/axios-miniprogram">
<img src="https://img.shields.io/bundlephobia/min/axios-miniprogram" alt="npm bundle size">
</a>
<a style="margin-left:5px;" href="https://opensource.org/licenses/MIT">
<img src="https://img.shields.io/github/license/zjx0905/axios-miniprogram" alt="license">
</a>
</p>
<p style="text-align: center;" align="center">
<a href='https://axios-miniprogram.com'>中文文档</a>
</p>
[中文文档](https://axios-miniprogram.com)
## axios-miniprogram 是什么?
@ -29,17 +27,16 @@ axios-miniprogram 是一款为小程序平台量身定制的轻量级请求库
## 特性
- 支持 `Typescript`,健全的类型系统,智能的 `IDE` 提示。
- 支持 动态地址。
- 支持 校验状态码。
- 支持 参数序列化。
- 支持 上传/下载。
- 支持 错误处理。
- 支持 转换数据。
- 支持 取消请求。
- 支持 扩展实例。
- 支持 中间件。
- 支持 `Promise`
- 支持 拦截器。
- 支持 平台适配器。
- 支持 取消请求。
- 支持 自定义合法状态码。
- 支持 自定义参数序列化。
- 支持 自定义转换数据。
- 支持 自定义错误处理。
- 支持 自定义平台适配器。
- 支持 上传/下载。
- 支持 派生领域。
## 目前内部支持的平台
@ -53,28 +50,17 @@ axios-miniprogram 是一款为小程序平台量身定制的轻量级请求库
- [飞书小程序](https://open.feishu.cn/document/uYjL24iN/uMjNzUjLzYzM14yM2MTN?from=axios-miniprogram)
- [快手小程序](https://mp.kuaishou.com/docs/introduction/quickStart.html?from=axios-miniprogram)
- [360 小程序](https://mp.360.cn/doc/miniprogram/dev/#/f4b41f0cc5683bce78dfadfa7f3c73e7?from=axios-miniprogram)
- [小红书小程序](https://miniapp.xiaohongshu.com/docs/guide/miniIntroduce?from=axios-miniprogram)
## 关于在跨端框架中使用时的支持度
问:在 uni-app 或者 Taro 等等这类跨端框架中使用时,该请求库支持 h5APPvue3 等等吗?
问:在 uni-app 或者 Taro 等等这类跨端框架中使用时,该请求库支持 h5APPvue3react 等等吗?
答:该请求库只是对框架提供的请求 API 进行了封装,并没有使用什么黑魔法。理论上来讲,框架支持的平台,该库也必然支持。
有问题欢迎反馈,请尽量把问题提到 [github issues](https://github.com/zjxxxxxxxxx/axios-miniprogram/issues) 中,这样更容易被我注意到。
有问题欢迎反馈,请尽量把问题提到 [github issues](https://github.com/zjx0905/axios-miniprogram/issues) 中,这样更容易被我注意到。
[提问点这里](https://github.com/zjxxxxxxxxx/axios-miniprogram/issues)
[提问点这里](https://github.com/zjx0905/axios-miniprogram/issues)
## 跨端框架示例
## 未来计划
### Taro
- [源代码](https://github.com/zjxxxxxxxxx/axios-miniprogram/tree/main/examples/taro)
- [CodeSandbox](https://codesandbox.io/p/sandbox/github/zjxxxxxxxxx/axios-miniprogram/tree/main/examples/taro)
- [StackBlitz](https://stackblitz.com/github/zjxxxxxxxxx/axios-miniprogram/tree/main/examples/taro)
### uni-app
- [源代码](https://github.com/zjxxxxxxxxx/axios-miniprogram/tree/main/examples/uni-app)
- [CodeSandbox](https://codesandbox.io/p/sandbox/github/zjxxxxxxxxx/axios-miniprogram/tree/main/examples/uni-app)
- [StackBlitz](https://stackblitz.com/github/zjxxxxxxxxx/axios-miniprogram/tree/main/examples/uni-app)
2023 年 6 月 1 日 起该库将不再内部支持第三方框架,内置的 uni-app 即将移除,您可以使用适配器兼容 uni-app。

View File

@ -18,10 +18,11 @@ export default defineConfig({
nav: [
{ text: '指南', link: '/guide/intro', activeMatch: '/guide/' },
{ text: '入门', link: '/basics/request', activeMatch: '/basics/' },
{ text: '请求方法', link: '/method/OPTIONS', activeMatch: '/method/' },
{ text: '基础', link: '/basics/config', activeMatch: '/basics/' },
{
text: '进阶',
link: '/advanced/middleware',
text: '高级',
link: '/advanced/request-interceptor',
activeMatch: '/advanced/',
},
],
@ -29,18 +30,15 @@ export default defineConfig({
sidebar: sidebar(),
socialLinks: [
{
icon: 'github',
link: 'https://github.com/zjxxxxxxxxx/axios-miniprogram',
},
{ icon: 'github', link: 'https://github.com/zjx0905/axios-miniprogram' },
],
editLink: {
pattern: ({ relativePath }) => {
if (relativePath.endsWith('/intro.md')) {
return 'https://github.com/zjxxxxxxxxx/axios-miniprogram/edit/main/README.md';
if (relativePath === 'intro.md') {
return 'https://github.com/zjx0905/axios-miniprogram/edit/main/README.md';
}
return `https://github.com/zjxxxxxxxxx/axios-miniprogram/edit/main/docs/pages/${relativePath}`;
return 'https://github.com/zjx0905/axios-miniprogram/edit/main/docs/pages/:path';
},
text: '在 GitHub 上编辑此页面',
},
@ -48,7 +46,7 @@ export default defineConfig({
algolia: algolia(),
returnToTopLabel: '返回顶部',
outlineTitle: '导航',
outlineTitle: '导航',
darkModeSwitchLabel: '主题',
sidebarMenuLabel: '菜单',
lastUpdatedText: '最后一次更新',
@ -58,9 +56,9 @@ export default defineConfig({
},
footer: {
message:
'根据 <a href="https://github.com/zjxxxxxxxxx/axios-miniprogram/blob/main/LICENSE">MIT License</a> 发布',
'根据 <a href="https://github.com/zjx0905/axios-miniprogram/blob/main/LICENSE">MIT License</a> 发布',
copyright:
'Copyright © 2020-至今 <a href="https://github.com/zjxxxxxxxxx">zjxxxxxxxxx</a>',
'Copyright © 2020-至今 <a href="https://github.com/zjx0905">zjx0905</a>',
},
},
@ -95,38 +93,6 @@ function sidebar() {
{ text: '开始', link: '/guide/quick-start' },
],
},
{
text: '入门',
items: [
{ text: '发送请求', link: '/basics/request' },
{ text: '响应体', link: '/basics/response' },
{ text: '错误处理', link: '/basics/error-handler' },
{ text: '动态地址', link: '/basics/dynamic-url' },
{ text: '请求配置', link: '/basics/config' },
{ text: '默认配置', link: '/basics/defaults' },
{ text: '参数系列化', link: '/basics/params-serializer' },
{ text: '转换数据', link: '/basics/transform-data' },
{ text: '下载文件', link: '/basics/download' },
{ text: '上传文件', link: '/basics/upload' },
],
collapsed: false,
},
{
text: '进阶',
items: [
{ text: '中间件', link: '/advanced/middleware' },
{ text: '请求拦截器', link: '/advanced/request-interceptor' },
{ text: '响应拦截器', link: '/advanced/response-interceptor' },
{ text: '取消请求', link: '/advanced/cancel' },
{ text: '创建实例', link: '/advanced/instance' },
{ text: '扩展实例', link: '/advanced/extend' },
{ text: '平台适配器', link: '/advanced/adapter' },
],
collapsed: false,
},
{
text: '请求方法',
items: [
@ -142,17 +108,41 @@ function sidebar() {
],
collapsed: false,
},
{
text: '基础',
items: [
{ text: '请求配置', link: '/basics/config' },
{ text: '响应体', link: '/basics/response' },
{ text: '发送请求', link: '/basics/request' },
{ text: '上传文件', link: '/basics/upload' },
{ text: '下载文件', link: '/basics/download' },
{ text: '错误处理', link: '/basics/error-handler' },
{ text: '取消请求', link: '/basics/cancel' },
],
collapsed: false,
},
{
text: '高级',
items: [
{ text: '请求拦截器', link: '/advanced/request-interceptor' },
{ text: '响应拦截器', link: '/advanced/response-interceptor' },
{ text: '创建实例', link: '/advanced/instance' },
{ text: '派生领域', link: '/advanced/fork' },
{ text: '适配器', link: '/advanced/adapter' },
],
collapsed: false,
},
{
text: '致贡献者',
items: [
{
text: '行为准则',
link: 'https://github.com/zjxxxxxxxxx/axios-miniprogram/blob/main/CODE_OF_CONDUCT.md',
link: 'https://github.com/zjx0905/axios-miniprogram/blob/main/CODE_OF_CONDUCT.md',
},
{
text: '贡献指南',
link: 'https://github.com/zjxxxxxxxxx/axios-miniprogram/blob/main/CONTRIBUTING.md',
link: 'https://github.com/zjx0905/axios-miniprogram/blob/main/CONTRIBUTING.md',
},
],
},
@ -162,7 +152,7 @@ function sidebar() {
function algolia() {
return {
appId: 'B2V3TSSQ2T',
apiKey: '2eddc4539ada25bf664eddcb91930736',
apiKey: 'c3edeb2daf09a254ec07ad98abfd84b5',
indexName: 'axios-miniprogram',
placeholder: '搜索文档',
translations: {

View File

@ -20,6 +20,7 @@
margin-top: var(--vp-nav-height);
padding-top: 40px !important;
height: calc(100% - var(--vp-nav-height));
border-right: 1px solid var(--vp-c-gutter);
transition: transform 0.3s cubic-bezier(0.19, 1, 0.22, 1) !important;
}
@ -62,34 +63,6 @@
left: 2px;
}
.VPDocAside .content {
border-left: none;
}
.VPDocAside .outline-title {
font-size: 14px;
font-weight: normal;
}
.VPDocAside .outline-marker {
left: 4px;
width: 4px;
height: 4px;
border-radius: 2px;
transform: translateY(7px);
}
.VPDocAside .outline-link {
position: relative;
font-weight: normal;
font-size: 14px;
}
.VPDocAside .outline-link.active {
color: var(--vp-c-brand);
font-weight: bold;
}
.VPBackdrop {
backdrop-filter: blur(16px);
background-color: transparent !important;
@ -148,6 +121,11 @@
}
.vp-code-group .tabs {
border-top: 1px;
border-left: 1px;
border-right: 1px;
border-bottom: 0;
border-style: solid;
border-color: var(--vp-c-gutter);
}
@ -164,13 +142,8 @@
box-shadow: none;
}
.DocSearch-Logo svg > * {
fill: currentColor;
}
.custom-block {
border-radius: 6px;
background-color: var(--vp-custom-block-tip-bg) !important;
}
.dark .DocSearch-Modal {
@ -181,10 +154,6 @@
background-color: var(--vp-code-block-bg);
}
.dark .DocSearch-Logo svg > * {
fill: currentColor;
}
@media (min-width: 960px) {
.VPFeatures .item {
width: calc(100% / 2) !important;
@ -205,14 +174,6 @@
.language-bash,
.language-ts {
border-radius: 6px;
}
.prev-next {
justify-content: space-between;
}
.pager {
width: auto !important;
min-width: 180px;
border: 1px solid var(--vp-c-gutter);
}
}

View File

@ -39,8 +39,7 @@
--vp-custom-block-tip-text: var(--vp-c-brand);
--vp-custom-block-tip-bg: var(--vp-c-bg);
--docsearch-container-background: rgba(0, 0, 0, 0.02);
--docsearch-logo-color: var(--vp-c-brand);
--docsearch-container-background: rgba(0, 0, 0, 0.1);
--vp-sidebar-width: 340px;
}
@ -68,9 +67,5 @@
--vp-code-copy-code-border-color: rgba(240, 246, 252, 0.1);
--vp-code-copy-code-hover-border-color: #8b949e;
--docsearch-container-background: rgba(255, 255, 255, 0.08);
}
.dark .DocSearch {
--docsearch-logo-color: var(--vp-c-brand);
--docsearch-container-background: rgba(255, 255, 255, 0.1);
}

View File

@ -1,4 +1,4 @@
import { linkSync, unlinkSync } from 'node:fs';
import { linkSync } from 'node:fs';
import { resolve } from '../../../scripts/utils';
const readmePath = resolve('README.md');
@ -6,9 +6,6 @@ const introPath = resolve('docs/pages/guide/intro.md');
export function linkIntro() {
try {
unlinkSync(introPath);
} catch {
//
}
linkSync(readmePath, introPath);
linkSync(readmePath, introPath);
} catch {}
}

View File

@ -7,11 +7,11 @@
"preview": "vitepress preview"
},
"devDependencies": {
"@types/lodash-es": "^4.17.7",
"vite-plugin-pwa": "^0.14.7",
"vitepress": "1.0.0-alpha.61"
},
"dependencies": {
"@types/lodash-es": "^4.17.7",
"lodash-es": "^4.17.21",
"vue": "^3.2.47"
}

View File

@ -1,289 +1,7 @@
---
title: 平台适配器
title: 适配器
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
用于支持更多小程序平台或小程序框架。
适配器是一个函数,它可以接收 `config` 参数。
:::
## 基本配置
可以接收基本配置。
```ts
import axios from 'axios-miniprogram';
axios.defaults.adapter = (config) => {
// 配置项
const {
// 请求类型
// 'request' | 'upload' | 'download'
type,
// 开发者服务器接口地址
url,
// HTTP 请求方法
method,
// 请求参数
params,
// 请求数据
data,
// 请求头
headers,
// 返回的数据格式
dataType,
// 响应的数据类型
responseType,
// 超时时间
timeout,
// 成功的回调
success,
// 失败的回调
fail,
} = config;
};
```
## 其他配置
可以接收任意多个其他配置。
```ts
import axios from 'axios-miniprogram';
axios.defaults.adapter = (config) => {
const {
// 其他配置
other1,
// 其他配置
other2,
} = config;
};
axios('https://api.com', {
other1: true,
other2: true,
});
```
## 实现一个适配器
适配的本质是对配置项进行转换,甚至可以零逻辑完成适配。
这里用适配 uni-app 举例,适配其他平台其实大同小异。
```ts
import axios from 'axios-miniprogram';
// 适配器
axios.defaults.adapter = (config) => {
// 可以先看看 config 上都有哪些属性
console.log(config);
// 开始适配不同类型的请求
switch (config.type) {
case 'request':
// 适配数据请求
return uni.request({
url: config.url,
data: config.data,
header: config.headers,
method: config.method,
timeout: config.timeout,
dataType: config.dataType,
responseType: config.responseType,
sslVerify: config.sslVerify,
withCredentials: config.withCredentials,
firstIpv4: config.firstIpv4,
enableHttp2: config.enableHttp2,
enableQuic: config.enableQuic,
enableCache: config.enableCache,
enableHttpDNS: config.enableHttpDNS,
httpDNSServiceId: config.httpDNSServiceId,
enableChunked: config.enableChunked,
forceCellularNetwork: config.forceCellularNetwork,
enableCookie: config.enableCookie,
cloudCache: config.cloudCache,
defer: config.defer,
success: (response) => {
config.success({
// 状态码
// 默认值200
status: response.statusCode,
// 响应头
// 默认值:{}
headers: response.header,
// 响应数据
data: response.data,
// cookie 列表
cookies: response.cookies,
});
},
fail: (error) => {
config.fail({
// 状态码
// 默认值400
status: 400,
// 响应头
// 默认值:{}
headers: {},
// 响应数据
// 平台 api 错误 error 通常是一个包含 errMsg 属性的对象
data: error,
});
},
});
case 'upload':
// 适配上传文件
const { files, fileType, file, filePath, name, ...formData } =
config.data;
return uni.uploadFile({
url: config.url,
files,
fileType,
file,
filePath,
name,
formData,
header: config.headers,
timeout: config.timeout,
success: (response) => {
config.success({
// 状态码
// 默认值200
status: response.statusCode,
// 响应头
// 默认值:{}
headers: response.header,
// 响应数据
data: response.data,
});
},
fail: (error) => {
config.fail({
// 状态码
// 默认值400
status: 400,
// 响应头
// 默认值:{}
headers: {},
// 响应数据
// 平台 api 错误 error 通常是一个包含 errMsg 属性的对象
data: error,
});
},
});
case 'download':
// 适配下载文件
return uni.downloadFile({
url: config.url,
filePath: config.params?.filePath,
header: config.headers,
timeout: config.timeout,
success: (response) => {
config.success({
// 状态码
// 默认值200
status: response.statusCode,
// 响应头
// 默认值:{}
headers: response.header,
// 响应数据
data: {
filePath: response.filePath,
tempFilePath: response.tempFilePath,
},
});
},
fail: (error) => {
config.fail({
// 状态码
// 默认值400
status: 400,
// 响应头
// 默认值:{}
headers: {},
// 响应数据
// 平台 api 错误 error 通常是一个包含 errMsg 属性的对象
data: error,
});
},
});
}
};
```
## 使用 `createAdapter` 创建适配器
可以使用 `createAdapter` 简化适配流程。
直接使用可以完美适配小程序平台,但不能保证完美适配小程序以外的其他平台,如 App、H5。
```ts
import axios from 'axios-miniprogram';
axios.defaults.adapter = axios.createAdapter({
request: uni.request,
upload: uni.uploadFile,
download: uni.downloadFile,
});
```
也可以进一步抹平存在差异的部分,实现完美适配全平台。
```ts
import axios from 'axios-miniprogram';
axios.defaults.adapter = axios.createAdapter({
request: uni.request,
upload: (config) => {
// 其实差异只有一点点,抹平可以很轻易~
const {
// 需要上传的文件列表
// App、H5 2.6.15+
files,
// 要上传的文件对象
// 仅 H52.6.15+)支持
file,
...formData
} = config.formData;
return uni.uploadFile({
...config,
files,
file,
formData,
});
},
download: uni.downloadFile,
});
```
待续...

View File

@ -1,255 +0,0 @@
---
title: 扩展实例
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
扩展新的实例,复用拦截器、中间件。
:::
## 扩展实例
可以基于 `axios` 扩展实例,配置项 `baseURL` 传相对地址时会和 `axios.defaults.baseURL` 一起组合成完整的服务端地址。
全局默认配置 `axios.defaults` 和扩展实例时传入的配置 `config` 将会按优先级[合并](/basics/defaults#配置合并策略)成实例默认配置 `instance.defaults`
```ts
import axios from 'axios-miniprogram';
axios.defaults.baseURL = 'https://api.com';
// 相对地址会进行组合
// baseURL 最终结果为 https://api.com/user
const instance = axios.extend({
baseURL: 'user',
headers: {
common: {
['Content-Type']: 'application/json',
},
post: {
['Content-Type']: 'application/x-www-form-urlencoded',
},
},
timeout: 1000,
});
// 绝对地址会直接使用
// baseURL 最终结果为 https://api2.com/user
const instance = axios.extend({
baseURL: 'https://api2.com/user',
headers: {
common: {
['Content-Type']: 'application/json',
},
post: {
['Content-Type']: 'application/x-www-form-urlencoded',
},
},
timeout: 1000,
});
```
## 默认配置
可以设置配置项默认值。
```ts
import axios from 'axios-miniprogram';
axios.defaults.baseURL = 'https://api.com';
const instance = axios.extend({
baseURL: 'user',
});
instance.defaults.headers.common['Content-Type'] = 'application/json';
instance.defaults.timeout = 1000;
```
## 添加拦截器
可以添加实例的[请求拦截器](/advanced/request-interceptor)和[响应拦截器](/advanced/response-interceptor)。
```ts
import axios from 'axios-miniprogram';
const instance = axios.extend({
baseURL: 'test',
});
// 请求拦截器
instance.interceptors.request.use(
function (config) {
console.log('instance request');
return config;
},
function (error) {
// 对请求错误做些什么
return Promise.reject(error);
},
);
// 响应拦截器
instance.interceptors.response.use(
function (response) {
console.log('instance response');
return response;
},
function (error) {
// 在 catch 之前做些什么
return Promise.reject(error);
},
);
// instance request -> instance response
instance('/');
```
也可以复用拦截器。
```ts
import axios from 'axios-miniprogram';
axios.defaults.baseURL = 'https://api.com';
const parent = axios.extend({
baseURL: '/parent',
});
const child = parent.extend({
baseURL: '/child',
});
// 请求拦截器
axios.interceptors.request.use(
function (config) {
console.log('axios request');
return config;
},
function (error) {
// 对请求错误做些什么
return Promise.reject(error);
},
);
// 响应拦截器
axios.interceptors.response.use(
function (response) {
console.log('axios response');
return response;
},
function (error) {
// 在 catch 之前做些什么
return Promise.reject(error);
},
);
// axios request -> https://api.com/parent/child/ -> axios response
child('/');
// 请求拦截器
parent.interceptors.request.use(
function (config) {
console.log('parent request');
return config;
},
function (error) {
// 对请求错误做些什么
return Promise.reject(error);
},
);
// 响应拦截器
parent.interceptors.response.use(
function (response) {
console.log('parent response');
return response;
},
function (error) {
// 在 catch 之前做些什么
return Promise.reject(error);
},
);
// axios request -> parent request -> https://api.com/parent/child/ -> parent response -> axios response
child('/');
// 请求拦截器
child.interceptors.request.use(
function (config) {
console.log('child request');
return config;
},
function (error) {
// 对请求错误做些什么
return Promise.reject(error);
},
);
// 响应拦截器
child.interceptors.response.use(
function (response) {
console.log('child response');
return response;
},
function (error) {
// 在 catch 之前做些什么
return Promise.reject(error);
},
);
// axios request -> parent request -> child request -> https://api.com/parent/child/ -> child response -> parent response -> axios response
child('/');
```
## 使用
使用方式和 `axios` 完全一致。
```ts
const instance = axios.extend({
baseURL: 'https://api.com',
});
instance('test')
.then((response) => {
// 请求成功后做些什么
})
.catch((error) => {
// 请求失败后做些什么
});
instance('test', {
method: 'POST',
})
.then((response) => {
// 请求成功后做些什么
})
.catch((error) => {
// 请求失败后做些什么
});
instance({
url: 'test',
method: 'POST',
})
.then((response) => {
// 请求成功后做些什么
})
.catch((error) => {
// 请求失败后做些什么
});
```
也可以使用请求方法简化请求。
- [instance.request(url, config?) | instance.request(config)](/basics/request)
- [instance.options(url, config?)](/method/OPTIONS)
- [instance.get(url, params?, config?)](/method/GET)
- [instance.head(url, params?, config?)](/method/HEAD)
- [instance.post(url, data?, config?)](/method/POST)
- [instance.put(url, data?, config?)](/method/PUT)
- [instance.patch(url, data?, config?)](/method/PATCH)
- [instance.delete(url, params?, config?)](/method/DELETE)
- [instance.trace(url, config?)](/method/TRACE)
- [instance.connect(url, config?)](/method/CONNECT)

View File

@ -0,0 +1,7 @@
---
title: 派生领域
---
# {{ $frontmatter.title }}
待续...

View File

@ -4,155 +4,4 @@ title: 创建实例
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
创建新的实例。
:::
## 创建实例
可以使用 `axios.create(config)` 创建新的实例。
全局默认配置 `axios.defaults` 和创建实例时传入的配置 `config` 将会按优先级[合并](/basics/defaults#配置合并策略)成实例默认配置 `instance.defaults`
```ts
import axios from 'axios-miniprogram';
const instance = axios.create({
baseURL: 'https://api2.com',
headers: {
common: {
['Content-Type']: 'application/json',
},
post: {
['Content-Type']: 'application/x-www-form-urlencoded',
},
},
timeout: 1000,
});
```
## 默认配置
可以设置配置项默认值。
```ts
import axios from 'axios-miniprogram';
const instance = axios.create({
baseURL: 'https://api2.com',
});
instance.defaults.headers.common['Content-Type'] = 'application/json';
instance.defaults.timeout = 1000;
```
## 添加拦截器
可以添加实例的[请求拦截器](/advanced/request-interceptor)和[响应拦截器](/advanced/response-interceptor)。
```ts
import axios from 'axios-miniprogram';
const instance = axios.create({
baseURL: 'https://api2.com',
});
// 请求拦截器
instance.interceptors.request.use(
function (config) {
// 在发送请求之前做些什么
return config;
},
function (error) {
// 对请求错误做些什么
return Promise.reject(error);
},
);
// 响应拦截器
instance.interceptors.response.use(
function (response) {
// 在 then 之前做些什么
return response;
},
function (error) {
// 在 catch 之前做些什么
return Promise.reject(error);
},
);
```
## 扩展实例
可以基于实例[扩展实例](/advanced/extend)。
实例默认配置 `parent.defaults` 和派生领域时传入的配置 `config` 将会按优先级[合并](/basics/defaults#配置合并策略)成新实例默认配置 `child.defaults`
```ts
import axios from 'axios-miniprogram';
const parent = axios.create({
baseURL: 'https://api2.com',
});
const child = instance.extend({
baseURL: 'user',
});
// 请求的服务端地址 https://api2.com/user
child('/');
```
## 使用
使用方式和 `axios` 完全一致。
```ts
import axios from 'axios-miniprogram';
const instance = axios.create({
baseURL: 'https://api.com',
});
instance('test')
.then((response) => {
// 请求成功后做些什么
})
.catch((error) => {
// 请求失败后做些什么
});
instance('test', {
method: 'POST',
})
.then((response) => {
// 请求成功后做些什么
})
.catch((error) => {
// 请求失败后做些什么
});
instance({
url: 'test',
method: 'POST',
})
.then((response) => {
// 请求成功后做些什么
})
.catch((error) => {
// 请求失败后做些什么
});
```
也可以使用请求方法简化请求。
- [instance.request(url, config?) | instance.request(config)](/basics/request)
- [instance.options(url, config?)](/method/OPTIONS)
- [instance.get(url, params?, config?)](/method/GET)
- [instance.head(url, params?, config?)](/method/HEAD)
- [instance.post(url, data?, config?)](/method/POST)
- [instance.put(url, data?, config?)](/method/PUT)
- [instance.patch(url, data?, config?)](/method/PATCH)
- [instance.delete(url, params?, config?)](/method/DELETE)
- [instance.trace(url, config?)](/method/TRACE)
- [instance.connect(url, config?)](/method/CONNECT)
待续...

View File

@ -1,123 +0,0 @@
---
title: 中间件
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
基于洋葱模型的中间件。
:::
## 前言
如果您了解或者使用过[koa](https://github.com/koajs/koa),相信您一定十分了解什么是洋葱模型,中间件该怎么写。
中间件是一个异步函数,接收 `context``next` 两个参数。
`context` 是一个对象,提供了 `req` 对象和 `res` 对象作为其组成部分。
- `context.req`:请求配置。
- `context.res`:请求完成后服务端返回的响应体,它的初始值是 `null`,请求完成之后才能对其进行操作。
`next` 是一个异步函数,如果希望程序继续执行后续逻辑,请手动调用它。
```ts
async (ctx, next) => {
// 请求发送前
const {
// 请求配置
req,
// 此时为 null
res,
} = ctx;
// 调用 next 继续执行后续逻辑,最终发送请求
await next();
// 请求完成后
const {
// 请求配置
req,
// 服务端返回的响应体
res,
} = ctx;
};
```
## 全局中间件
可以添加全局中间件,对发送的每个请求生效。
```ts
import axios from 'axios-miniprogram';
// use 会返回 this可以链式添加多个
axios
.use(async (ctx, next) => {
console.log('1');
await next();
console.log('4');
})
.use(async (ctx, next) => {
console.log('2');
await next();
console.log('3');
});
// 洋葱模型执行顺序
// 1 -> 2 -> /test -> 3 -> 4
axios('/test');
```
## 实例中间件
可以为实例添加中间件,对实例发送的每个请求生效。
```ts
import axios from 'axios-miniprogram';
const instance = axios.create({
baseURL: 'https://api.com',
});
instance.use(async (ctx, next) => {
console.log('instance request');
await next();
console.log('instance response');
});
// instance request -> https://api.com/test -> instance response
instance('https://api.com/test');
```
## 扩展实例中间件
可以为扩展实例添加中间件,扩展实例同时也可以复用父级中间件。
```ts
import axios from 'axios-miniprogram';
axios.defaults.baseURL = 'https://api.com';
axios.use(async (ctx, next) => {
console.log('axios request');
await next();
console.log('axios response');
});
const instance = axios.extend({
baseURL: '/test',
});
instance.use(async (ctx, next) => {
console.log('instance request');
await next();
console.log('instance response');
});
// 复用父级中间件
// axios request -> instance request -> https://api.com/test/user -> instance response -> axios response
instance('/user');
```

View File

@ -4,112 +4,4 @@ title: 请求拦截器
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
用于请求发送前拦截请求。
通常会用于转换请求配置,或实现一些自定义功能。
:::
## 添加请求拦截器
可以添加请求拦截器。
```ts
import axios from 'axios-miniprogram';
axios.interceptors.request.use(
function (config) {
// 在发送请求之前做些什么
return config;
},
function (error) {
// 对请求错误做些什么
return Promise.reject(error);
},
);
```
也可以添加多个请求拦截器,后添加的会先执行。
```ts
import axios from 'axios-miniprogram';
// 先添加 后执行
axios.interceptors.request.use(
function (config) {
// 在发送请求之前做些什么
return config;
},
function (error) {
// 对请求错误做些什么
return Promise.reject(error);
},
);
// 后添加 先执行
axios.interceptors.request.use(
function (config) {
// 在发送请求之前做些什么
return config;
},
function (error) {
// 对请求错误做些什么
return Promise.reject(error);
},
);
```
## 移除请求拦截器
可以移除不再需要的请求拦截器。
```ts
import axios from 'axios-miniprogram';
const ejectId = axios.interceptors.request.use(
function (config) {
// 在发送请求之前做些什么
return config;
},
function (error) {
// 对请求错误做些什么
return Promise.reject(error);
},
);
// 移除请求拦截器
axios.interceptors.request.eject(ejectId);
```
## 移除所有请求拦截器
可以移除所有请求拦截器。
```ts
import axios from 'axios-miniprogram';
axios.interceptors.request.use(
function (config) {
// 在发送请求之前做些什么
return config;
},
function (error) {
// 对请求错误做些什么
return Promise.reject(error);
},
);
axios.interceptors.request.use(
function (config) {
// 在发送请求之前做些什么
return config;
},
function (error) {
// 对请求错误做些什么
return Promise.reject(error);
},
);
// 移除所有请求拦截器
axios.interceptors.request.clear();
```
待续...

View File

@ -4,112 +4,4 @@ title: 响应拦截器
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
用于 `response` 到达 `then` 之前,或 `error` 到达 `catch` 之前拦截响应。
通常会用于处理错误,但对于处理错误而言,使用 `errorHandler` 会是更好的选择。
:::
## 添加响应拦截器
可以添加响应拦截器。
```ts
import axios from 'axios-miniprogram';
axios.interceptors.response.use(
function (response) {
// 在 then 之前做些什么
return response;
},
function (error) {
// 在 catch 之前做些什么
return Promise.reject(error);
},
);
```
也可以添加多个响应拦截器,先添加的会先执行。
```ts
import axios from 'axios-miniprogram';
// 先添加 先执行
axios.interceptors.response.use(
function (response) {
// 在 then 之前做些什么
return response;
},
function (error) {
// 在 catch 之前做些什么
return Promise.reject(error);
},
);
// 后添加 后执行
axios.interceptors.response.use(
function (response) {
// 在 then 之前做些什么
return response;
},
function (error) {
// 在 catch 之前做些什么
return Promise.reject(error);
},
);
```
## 移除响应拦截器
可以移除不再需要的响应拦截器。
```ts
import axios from 'axios-miniprogram';
const ejectId = axios.interceptors.response.use(
function (response) {
// 在 then 之前做些什么
return response;
},
function (error) {
// 在 catch 之前做些什么
return Promise.reject(error);
},
);
// 移除响应拦截器
axios.interceptors.response.eject(ejectId);
```
## 移除所有响应拦截器
可以移除所有响应拦截器。
```ts
import axios from 'axios-miniprogram';
axios.interceptors.response.use(
function (response) {
// 在 then 之前做些什么
return response;
},
function (error) {
// 在 catch 之前做些什么
return Promise.reject(error);
},
);
axios.interceptors.response.use(
function (response) {
// 在 then 之前做些什么
return response;
},
function (error) {
// 在 catch 之前做些什么
return Promise.reject(error);
},
);
// 移除所有响应拦截器
axios.interceptors.response.clear();
```
待续...

View File

@ -35,7 +35,7 @@ cancel('request canceled');
## 工厂方法
可以用 `CancelToken.source` 工厂方法创建 `CancelToken` 实例用来取消请求。
可以用 `CancelToken.source` 工厂方法创建 `CancelToken` 实例用来取消请求。
```ts
import axios from 'axios-miniprogram';
@ -55,9 +55,9 @@ axios('https://api.com/test', {
cancel('request canceled');
```
## 判断取消请求
## 判断异常是否来自取消请求
可以判断请求错误是否来自取消请求,从而做出相应的处理。
也可以用 `axios.isCancel` 判断异常是否来自取消请求,从而做出相应的处理。
```ts
import axios from 'axios-miniprogram';
@ -70,7 +70,6 @@ axios('https://api.com/test', {
// 成功之后做些什么
})
.catch((error) => {
// 判断取消请求
if (axios.isCancel(error)) {
console.log(error, '请求已被取消');
}

View File

@ -8,9 +8,9 @@ title: 请求配置
用于自定义请求行为。
:::
## 通用配置项
## 通用属性
可以设置这些配置项
可以设置这些属性
```ts
import axios from 'axios-miniprogram';
@ -103,9 +103,9 @@ axios({
});
```
## 平台配置项
## 平台属性
可以设置平台特有的配置项,具体情况取决于平台特性。
也可以设置平台特有属性,具体情况取决于平台特性。
微信小程序示例:
@ -144,51 +144,21 @@ axios({
想要了解更多请自行参阅对应平台文档。
## 自定义配置项
## 自定义属性
可以设置自定义配置项,从而实现一些自定义功能
也可以设置自定义属性
自定义配置项可以根据需要随意设置。
自定义属性可以根据需要随意设置。
```ts
import axios from 'axios-miniprogram';
// 错误处理
axios.defaults.errorHandler = (error) => {
if (axios.isAxiosError(error)) {
// 显示错误信息
if (error.config.showError) {
wx.showToast({
title: error.response.data.errMsg,
});
}
}
};
// 请求拦截器
axios.interceptors.request.use((config) => {
// 自动显示 loading
if (config.showLoading) {
wx.showLoading();
}
return config;
});
// 响应拦截器
axios.interceptors.response.use((response) => {
// 自动隐藏 loading
if (response.config.showLoading) {
wx.hideLoading();
}
return response;
});
axios({
// 请求时自动 loading
showLoading: true,
// 这是一个自定义配置
user: '123',
// 出错时显示错误信息
showError: true,
// 这也是一个自定义配置
showLoading: true,
})
.then((response) => {
// 成功之后做些什么

View File

@ -1,177 +0,0 @@
---
title: 默认配置
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
用于设置作用于每个请求的配置项默认值。
[配置合并策略](/basics/defaults#配置合并策略)
:::
## 默认值
在不更改默认配置的情况下,它依然会存在一些默认值,在 [defaults.ts](https://github.com/zjxxxxxxxxx/axios-miniprogram/blob/main/src/defaults.ts) 中定义,大概长下面这样。
```ts
{
// 适配器,在支持的平台中有值。
// 对于不支持平台而言,此值始终为 undefined需要您手动适配。
adapter: getDefaultAdapter(),
// 请求头
headers: {
// 通用请求头
common: {
Accept: 'application/json, text/plain, */*',
},
options: {}, // OPTIONS 方法请求头
get: {}, // GET 方法请求头
head: {}, // HEAD 方法请求头
post: {}, // POST 方法请求头
put: {}, // PUT 方法请求头
patch: {}, // PATCH 方法请求头
delete: {}, // DELETE 方法请求头
trace: {}, // TRACE 方法请求头
connect: {}, // CONNECT 方法请求头
},
// 校验状态码
validateStatus(status: number): boolean {
return status >= 200 && status < 300;
},
// 返回的数据格式
dataType: 'json',
// 响应的数据类型
responseType: 'text',
// 超时时长
timeout: 10000,
}
```
## 设置配置项
可以设置配置项默认值。
列举部分示例:
```ts
import axios from 'axios-miniprogram';
// 基础服务器地址
axios.defaults.baseURL = 'https://api.com';
// 通用请求头
axios.defaults.headers.common['Content-Type'] = 'application/json';
// POST 方法请求头
axios.defaults.headers.post['Content-Type'] =
'application/x-www-form-urlencoded';
// 超时时间
axios.defaults.timeout = '60000';
// 校验状态码
axios.defaults.validateStatus = (status) => {
return status === 200;
};
// 错误处理
axios.defaults.errorHandler = (error) => {
console.log('出错了');
};
// 监听上传进度
axios.defaults.onUploadProgress = (event) => {
console.log('上传中:' + event.progress);
};
```
## 设置平台配置项
可以设置平台特有配置项默认值,具体情况取决于平台特性。
微信小程序示例:
```ts
import axios from 'axios-miniprogram';
// 开启 http2
axios.defaults.enableHttp2 = true;
// 开启 quic
axios.defaults.enableQuic = true;
// 开启 cache
axios.defaults.enableCache = true;
// 开启 HttpDNS 服务。
axios.defaults.enableHttpDNS = true;
// HttpDNS 服务商 Id。
axios.defaults.httpDNSServiceId = '123';
// wifi 下使用移动网络发送请求
axios.defaults.forceCellularNetwork = false;
```
想要了解更多请自行参阅对应平台文档。
## 设置自定义配置项
可以设置自定义配置项默认值。
```ts
import axios from 'axios-miniprogram';
// 出错时显示错误信息
axios.defaults.showError = true;
// 请求时自动 loading
axios.defaults.showLoading = true;
// 错误处理
axios.defaults.errorHandler = (error) => {
if (axios.isAxiosError(error)) {
// 显示错误信息
if (error.config.showError) {
wx.showToast({
title: error.response.data.errMsg,
});
}
}
};
// 请求拦截器
axios.interceptors.request.use((config) => {
// 自动显示 loading
if (config.showLoading) {
wx.showLoading();
}
return config;
});
// 响应拦截器
axios.interceptors.response.use((response) => {
// 自动隐藏 loading
if (response.config.showLoading) {
wx.hideLoading();
}
return response;
});
```
## 配置合并策略
默认配置和请求配置将会按优先级进行合并。
其中:
1. `url`、`method`、`data`、`upload`、`download` 只从 `config` 取值。
2. `headers`、`params` 会分别进行深度合并。
3. 其余属性则会优先从 `config` 取值。
具体配置合并策略请参阅 [mergeConfig.ts](https://github.com/zjxxxxxxxxx/axios-miniprogram/blob/main/src/core/mergeConfig.ts) 。

View File

@ -5,11 +5,7 @@ title: 下载文件
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
下载文件资源到本地。
:::
::: warning 注意
下载文件只能使用 `GET` 方法请求,并将配置项 `download` 设置为 `true`
下载文件资源到本地,必须使用 `GET` 方法请求,并将请求配置的 `download` 属性设置为 `true`
:::
## 普通的下载请求
@ -19,14 +15,19 @@ title: 下载文件
```ts
import axios from 'axios-miniprogram';
axios('https://api.com/test', {
download: true,
})
axios
.get(
'https://api.com/test',
{},
{
download: true,
},
)
.then((response) => {
const {
// 临时文件路径 (本地路径)。没传入 filePath 指定文件存储路径时会返回,下载后的文件会存储到一个临时文件
tempFilePath,
} = response.data;
} = response;
})
.catch((error) => {
// 失败之后做些什么
@ -35,22 +36,26 @@ axios('https://api.com/test', {
## 携带参数的下载请求
可以指定文件下载后存储的路径 (本地路径)。
可以指定文件下载后存储的路径 (本地路径)。
```ts
import axios from 'axios-miniprogram';
axios('https://api.com/test', {
download: true,
params: {
filePath: '你的本地路径',
},
})
axios
.get(
'https://api.com/test',
{
filePath: '你的本地路径',
},
{
download: true,
},
)
.then((response) => {
const {
// 指定文件下载后存储的路径 (本地路径)
filePath,
} = response.data;
} = response;
})
.catch((error) => {
// 失败之后做些什么
@ -59,34 +64,38 @@ axios('https://api.com/test', {
## 监听下载进度
可以监听下载进度变化。
可以监听下载进度变化。
```ts
import axios from 'axios-miniprogram';
axios('https://api.com/test', {
download: true,
params: {
filePath: '你的本地路径',
},
onDownloadProgress(event) {
const {
// 下载进度百分比
progress,
axios
.get(
'https://api.com/test',
{
filePath: '你的本地路径',
},
{
download: true,
onDownloadProgress(event) {
const {
// 下载进度
progress,
// 已经下载的数据长度,单位 Bytes
totalBytesWritten,
// 已经下载的数据长度
totalBytesSent,
// 预预期需要下载的数据总长度,单位 Bytes
totalBytesExpectedToWrite,
} = event;
},
})
// 预期需要下载的数据总长度
totalBytesExpectedToSend,
} = event;
},
},
)
.then((response) => {
const {
// 指定文件下载后存储的路径 (本地路径)
filePath,
} = response.data;
} = response;
})
.catch((error) => {
// 失败之后做些什么

View File

@ -1,100 +0,0 @@
---
title: 动态地址
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
简化地址参数的设置方式。
:::
## 设置请求参数
可以设置请求参数,最终会从请求参数中获取对应的值。
::: warning 注意
获取到值后会从请求参数中删除对应的值。
:::
```ts
import axios from 'axios-miniprogram';
// 请求的服务端地址 https://api.com/1
// 获取到 id 之后,会从 params 中删除 id
axios('https://api.com/:id', {
params: {
id: 1,
},
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 设置请求数据
可以设置请求数据,最终会从请求数据中获取对应的值。
```ts
import axios from 'axios-miniprogram';
// 请求的服务端地址 https://api.com/1
// 获取到 id 之后,不会从 data 中删除 id
axios('https://api.com/:id', {
method: 'POST',
data: {
id: 1,
},
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 同时设置请求参数和请求数据
可以同时设置请求参数和请求数据,会优先从请求参数中获取对应的值。
```ts
import axios from 'axios-miniprogram';
// 请求的服务端地址 https://api.com/1
axios('https://api.com/:id', {
method: 'POST',
params: {
id: 1,
},
data: {
id: 2,
},
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
// 请求的服务端地址 https://api.com/1/test
axios('https://api.com/:id/:name', {
method: 'POST',
params: {
id: 1,
},
data: {
name: 'test',
},
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```

View File

@ -8,16 +8,17 @@ title: 错误处理
当请求失败时,可以对错误进行处理。
:::
## 校验状态抛出错误
## 使用 `validateStatus` 抛出错误
可以设置校验状态,自定义抛出错误的状态码
可以使用 `validateStatus` 自定义抛出错误的 HTTP code
```ts
import axios from 'axios-miniprogram';
axios('https://api.com/test', {
validateStatus(status) {
return status === 200;
// status 小于 200 大于 299 会抛出错误
return status >= 200 && status < 300;
},
})
.then((response) => {
@ -28,7 +29,7 @@ axios('https://api.com/test', {
});
```
## `catch` 处理错误
## `catch`处理错误
可以处理不同类型的错误。
@ -67,12 +68,10 @@ axios('https://api.com/test')
} else {
// 其他错误
}
return Promise.reject(error);
});
```
## 用 `errorHandler` 处理错误
## 使`errorHandler` 处理错误
可以使用 `errorHandler` 处理不同类型的错误。
@ -108,8 +107,6 @@ axios('https://api.com/test', {
} else {
// 其他错误
}
return Promise.reject(error);
},
})
.then((response) => {
@ -119,44 +116,3 @@ axios('https://api.com/test', {
// 失败之后做些什么
});
```
## 全局错误处理
可以设置全局错误处理,对每个请求生效。
```ts
import axios from 'axios-miniprogram';
// 全局错误处理
axios.defaults.errorHandler = (error) => {
if (axios.isAxiosError(error)) {
// 响应错误
const {
// 错误消息
message,
// 请求配置
config,
// 请求任务,也就是请求函数返回的结果
request,
// 响应体
response,
} = error;
if (response.isFail) {
// 平台或适配器错误
} else {
// 使用 `validateStatus` 自定义抛出的错误
}
} else if (axios.isCancel(error)) {
// 取消请求
} else {
// 其他错误
}
return Promise.reject(error);
};
```

View File

@ -1,33 +0,0 @@
---
title: 参数系列化
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
支持自定义参数系列化器。
:::
## 自定义参数系列化器
可以用自己的方式系列化参数。
```ts
import axios from 'axios-miniprogram';
import qs from 'qs';
axios('https://api.com', {
params: {
id: 1,
},
paramsSerializer(params) {
return qs.stringify(params);
},
})
.then((response) => {
// 请求成功后做些什么
})
.catch((error) => {
// 请求失败后做些什么
});
```

View File

@ -27,7 +27,7 @@ axios
## 携带请求配置
可以额外传递第二个参数 `config`,用于指定请求方法以及其他配置项。
可以传递第二个参数 `config`,用于指定请求方法以及其他配置项。
```ts
import axios from 'axios-miniprogram';
@ -50,7 +50,7 @@ axios
## 仅有请求配置
可以直接传递 `config` 发送请求。
可以忽略以上示例,直接传递 `config` 发送请求。
```ts
import axios from 'axios-miniprogram';
@ -70,20 +70,6 @@ axios
});
```
## 请求方法
提供一系列基于 `axios.request()` 的请求方法,可以使用请求方法简化请求。
- [axios.options(url, config?)](/method/OPTIONS)
- [axios.get(url, params?, config?)](/method/GET)
- [axios.head(url, params?, config?)](/method/HEAD)
- [axios.post(url, data?, config?)](/method/POST)
- [axios.put(url, data?, config?)](/method/PUT)
- [axios.patch(url, data?, config?)](/method/PATCH)
- [axios.delete(url, params?, config?)](/method/DELETE)
- [axios.trace(url, config?)](/method/TRACE)
- [axios.connect(url, config?)](/method/CONNECT)
## 说明
您可能发现 `axios.request()``axios()` 使用方式完全一致,为什么用法是一样的?

View File

@ -44,7 +44,7 @@ axios('https//api.com')
## 平台属性
请求成功返回的 `response` 可能带有平台特有的属性,具体情况取决于平台特性。
请求成功返回的 `response` 可能带有平台特有的属性,具体情况取决于平台特性。
微信小程序示例:

View File

@ -1,121 +0,0 @@
---
title: 转换数据
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
请求发送前转换请求数据,响应到达 `then` 之前转换响应数据。
:::
## 转换请求数据
可以转换请求数据,只对允许携带请求数据的请求方法生效,允许携带请求数据的方法有:`POST`、`PUT`、`PATCH`。
```ts
import axios from 'axios-miniprogram';
axios('test', {
method: 'POST',
transformRequest(data, headers) {
return JSON.stringify(data);
},
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
也支持多次转换。
```ts
import axios from 'axios-miniprogram';
axios('test', {
method: 'POST',
transformRequest: [
(data, headers) => {
return JSON.stringify(data);
},
(data, headers) => {
return encodeURIComponent(data);
},
],
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 全局转换请求数据
可以设置全局转换请求数据,对每个请求生效。
```ts
import axios from 'axios-miniprogram';
axios.defaults.transformRequest = (data, headers) => {
return JSON.stringify(data);
};
```
## 转换响应数据
可以转换响应数据。
```ts
import axios from 'axios-miniprogram';
axios('test', {
transformResponse(data, headers) {
return JSON.parse(data);
},
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
也支持多次转换。
```ts
import axios from 'axios-miniprogram';
axios('test', {
transformResponse: [
(data, headers) => {
return decodeURIComponent(data);
},
(data, headers) => {
return JSON.parse(data);
},
],
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
## 全局转换响应数据
可以设置全局转换响应数据,对每个请求生效。
```ts
import axios from 'axios-miniprogram';
axios.defaults.transformResponse = (data, headers) => {
return JSON.parse(data);
};
```

View File

@ -5,11 +5,7 @@ title: 上传文件
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
将本地资源上传到服务器。
:::
::: warning 注意
上传文件只能使用 `POST` 方法请求,并将请求配置项 `upload` 设置为 `true`
将本地资源上传到服务器,必须使用 `POST` 方法请求,并将请求配置的 `upload` 属性设置为 `true`
:::
## 普通的上传请求
@ -19,17 +15,20 @@ title: 上传文件
```ts
import axios from 'axios-miniprogram';
axios('https://api.com/test', {
method: 'POST',
upload: true,
data: {
// 文件对应的 key开发者在服务端可以通过这个 key 获取文件的二进制内容
name: 'fileName',
axios
.post(
'https://api.com/test',
{
// 文件对应的 key开发者在服务端可以通过这个 key 获取文件的二进制内容
name: 'fileName',
// 要上传文件资源的路径 (本地路径)
filePath: '你的本地路径',
},
})
// 要上传文件资源的路径 (本地路径)
filePath: '你的本地路径',
},
{
upload: true,
},
)
.then((response) => {
const {
// 开发者服务器返回的数据
@ -48,23 +47,26 @@ axios('https://api.com/test', {
```ts
import axios from 'axios-miniprogram';
axios('https://api.com/test', {
method: 'POST',
upload: true,
data: {
// 文件对应的 key开发者在服务端可以通过这个 key 获取文件的二进制内容
name: 'fileName',
axios
.post(
'https://api.com/test',
{
// 文件对应的 key开发者在服务端可以通过这个 key 获取文件的二进制内容
name: 'fileName',
// 要上传文件资源的路径 (本地路径)
filePath: '你的本地路径',
// 要上传文件资源的路径 (本地路径)
filePath: '你的本地路径',
// 这是额外的 formData 属性
id: 1,
// 这是额外的 formData 属性
id: 1,
// 这是额外的 formData 属性
user: '123',
},
})
// 这是额外的 formData 属性
user: '123',
},
{
upload: true,
},
)
.then((response) => {
const {
// 开发者服务器返回的数据
@ -83,35 +85,38 @@ axios('https://api.com/test', {
```ts
import axios from 'axios-miniprogram';
axios('https://api.com/test', {
method: 'POST',
upload: true,
data: {
// 文件对应的 key开发者在服务端可以通过这个 key 获取文件的二进制内容
name: 'fileName',
axios
.post(
'https://api.com/test',
{
// 文件对应的 key开发者在服务端可以通过这个 key 获取文件的二进制内容
name: 'fileName',
// 要上传文件资源的路径 (本地路径)
filePath: '你的本地路径',
// 要上传文件资源的路径 (本地路径)
filePath: '你的本地路径',
// 这是额外的 formData 属性
id: 1,
// 这是额外的 formData 属性
id: 1,
// 这是额外的 formData 属性
user: '123',
},
onUploadProgress(event) {
const {
// 上传进度百分比
progress,
// 这是额外的 formData 属性
user: '123',
},
{
upload: true,
onUploadProgress(event) {
const {
// 上传进度
progress,
// 已经上传的数据长度,单位 Bytes
totalBytesSent,
// 已经上传的数据长度
totalBytesSent,
// 预期需要上传的数据总长度,单位 Bytes
totalBytesExpectedToSend,
} = event;
},
})
// 预期需要上传的数据总长度
totalBytesExpectedToSend,
} = event;
},
},
)
.then((response) => {
const {
// 开发者服务器返回的数据

View File

@ -9,107 +9,39 @@ title: 开始
:::: code-group
```bash [NPM]
$ npm install axios-miniprogram
$ npm install -D axios-miniprogram
```
```bash [YARN]
$ yarn add axios-miniprogram
$ yarn add -D axios-miniprogram
```
```bash [PNPM]
$ pnpm install axios-miniprogram
$ pnpm install -D axios-miniprogram
```
::::
原生小程序也可以直接[下载源码包](https://github.com/zjxxxxxxxxx/axios-miniprogram/releases),但是这样是失去类型提示和 `sourceMap` 定位功能。
建议在条件允许的情况下优先使用包管理工具安装的方式,而不是使用下载源码包的方式。
[原生小程序也可以直接下载源码包](https://github.com/zjx0905/axios-miniprogram/releases)
## 引用
可以在不同的模块系统导入需要用到的功能。
:::: code-group
```ts [ES Module]
import axios, {
// 取消令牌
CancelToken,
import axios from 'axios-miniprogram';
// 判断取消请求错误
isCancel,
// 原始 Axios 类
Axios,
// 判断请求响应错误
isAxiosError,
// 创建平台适配器
createAdapter,
} from 'axios-miniprogram';
axios('/test');
axios('test');
```
```ts [CommonJS]
const {
// 静态对象
// 注意:默认导出的 axios 在 CommonJS 里是以 default 属性的方式存在
default: axios,
const axios = require('axios-miniprogram').default;
// 取消令牌
CancelToken,
// 判断取消请求错误
isCancel,
// 原始 Axios 类
Axios,
// 判断请求响应错误
isAxiosError,
// 创建平台适配器
createAdapter,
} = require('axios-miniprogram');
axios('/test');
axios('test');
```
::::
不同的模块系统存在一些小差异,`esm` 会自动处理默认导入,但 `cjs` 不会处理默认导入。
```ts
// 默认导入esm 和 cjs 这两种写法是等价关系
import axios from 'axios-miniprogram';
const axios = require('axios-miniprogram').default;
// 别名导入esm 和 cjs 这两种写法是等价关系
import * as axios from 'axios-miniprogram';
const axios = require('axios-miniprogram');
// 具名导入esm 和 cjs 这两种写法是等价关系
import {
default as axios,
CancelToken,
isCancel,
Axios,
isAxiosError,
createAdapter,
} from 'axios-miniprogram';
const {
default: axios,
CancelToken,
isCancel,
Axios,
isAxiosError,
createAdapter,
} = require('axios-miniprogram');
```
## 使用
### `axios(url, config?)`
@ -185,3 +117,10 @@ axios({
- [axios.delete(url, params?, config?)](/method/DELETE)
- [axios.trace(url, config?)](/method/TRACE)
- [axios.connect(url, config?)](/method/CONNECT)
还提供了一系列工具方法。
- `axios.create(defaults?)` 创建新的 `axios` 实例
- `axios.createAdapter(platform)` 创建平台适配器
- `axios.isCancel(error)` 判断异常是否来自取消请求
- `axios.isAxiosError(error)` 判断异常是否来自请求响应

View File

@ -19,7 +19,7 @@ features:
details: 包尺寸仅 10 kb不会占用您太多空间
icon: 🤌
- title: 简单易用
details: 提供了简易的 API并且具有很强的可拓展性
details: 提供了简的 API并且具有很强的可拓展性
icon: 🎯
- title: 方便快捷
details: 除了提供 npm 安装包以外,还为原生小程序提供开箱即用的源码包

View File

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

View File

@ -1,2 +0,0 @@
FROM node:16
RUN npm i -g pnpm

View File

@ -1,15 +0,0 @@
{
"setupTasks": [
{
"name": "Install Dependencies",
"command": "pnpm i"
}
],
"tasks": {
"dev": {
"name": "dev",
"command": "pnpm dev:h5",
"runAtStart": true
}
}
}

View File

@ -1,8 +0,0 @@
{
"extends": ["taro/react"],
"rules": {
"react/jsx-uses-react": "off",
"react/react-in-jsx-scope": "off",
"jsx-quotes": "off"
}
}

View File

@ -1,7 +0,0 @@
dist/
deploy_versions/
.temp/
.rn_temp/
node_modules/
.DS_Store
.swc

View File

@ -1,15 +0,0 @@
import type { UserConfigExport } from '@tarojs/cli';
export default {
logger: {
quiet: false,
stats: true,
},
mini: {},
h5: {
devServer: {
port: 3000,
allowedHosts: 'all',
},
},
} satisfies UserConfigExport;

View File

@ -1,102 +0,0 @@
import { defineConfig, type UserConfigExport } from '@tarojs/cli';
import TsconfigPathsPlugin from 'tsconfig-paths-webpack-plugin';
import devConfig from './dev';
import prodConfig from './prod';
// https://taro-docs.jd.com/docs/next/config#defineconfig-辅助函数
export default defineConfig(async (merge) => {
const baseConfig: UserConfigExport = {
projectName: 'axios',
designWidth: 750,
deviceRatio: {
640: 2.34 / 2,
750: 1,
375: 2,
828: 1.81 / 2,
},
sourceRoot: 'src',
outputRoot: `dist/${process.env.TARO_ENV}`,
plugins: [
'@tarojs/plugin-platform-alipay-dd',
'@tarojs/plugin-platform-lark',
'@tarojs/plugin-platform-kwai',
],
defineConstants: {},
copy: {
patterns: [],
options: {},
},
framework: 'react',
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]',
},
},
},
webpackChain(chain) {
chain.resolve.plugin('tsconfig-paths').use(TsconfigPathsPlugin);
},
},
h5: {
publicPath: '/',
staticDirectory: 'static',
output: {
filename: 'js/[name].[hash:8].js',
chunkFilename: 'js/[name].[chunkhash:8].js',
},
miniCssExtractPluginOption: {
ignoreOrder: true,
filename: 'css/[name].[hash].css',
chunkFilename: 'css/[name].[chunkhash].css',
},
postcss: {
autoprefixer: {
enable: true,
config: {},
},
cssModules: {
enable: false, // 默认为 false如需使用 css modules 功能,则设为 true
config: {
namingPattern: 'module', // 转换模式,取值为 global/module
generateScopedName: '[name]__[local]___[hash:base64:5]',
},
},
},
webpackChain(chain) {
chain.resolve.plugin('tsconfig-paths').use(TsconfigPathsPlugin);
},
},
rn: {
appName: 'taroDemo',
postcss: {
cssModules: {
enable: false, // 默认为 false如需使用 css modules 功能,则设为 true
},
},
},
};
if (process.env.NODE_ENV === 'development') {
// 本地开发构建配置(不混淆压缩)
return merge({}, baseConfig, devConfig);
}
// 生产构建配置(默认开启压缩混淆等)
return merge({}, baseConfig, prodConfig);
});

View File

@ -1,33 +0,0 @@
import type { UserConfigExport } from '@tarojs/cli';
export default {
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') })
// }))
// }
},
} satisfies UserConfigExport;

View File

@ -1,79 +0,0 @@
{
"private": true,
"name": "@examples/taro",
"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:dd": "taro build --type dd",
"build:lark": "taro build --type lark",
"build:kwai": "taro build --type kwai",
"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:dd": "npm run build:dd -- --watch",
"dev:lark": "npm run build:lark -- --watch",
"dev:kwai": "npm run build:kwai -- --watch",
"dev:quickapp": "npm run build:quickapp -- --watch"
},
"dependencies": {
"@babel/core": "^7.8.0",
"@babel/runtime": "^7.21.5",
"@pmmmwh/react-refresh-webpack-plugin": "^0.5.5",
"@tarojs/cli": "3.6.13",
"@tarojs/components": "3.6.13",
"@tarojs/helper": "3.6.13",
"@tarojs/plugin-framework-react": "3.6.13",
"@tarojs/plugin-platform-alipay": "3.6.13",
"@tarojs/plugin-platform-alipay-dd": "^0.3.0",
"@tarojs/plugin-platform-h5": "3.6.13",
"@tarojs/plugin-platform-jd": "3.6.13",
"@tarojs/plugin-platform-kwai": "^6.0.0",
"@tarojs/plugin-platform-lark": "^1.1.4",
"@tarojs/plugin-platform-qq": "3.6.13",
"@tarojs/plugin-platform-swan": "3.6.13",
"@tarojs/plugin-platform-tt": "3.6.13",
"@tarojs/plugin-platform-weapp": "3.6.13",
"@tarojs/react": "3.6.13",
"@tarojs/runtime": "3.6.13",
"@tarojs/shared": "3.6.13",
"@tarojs/taro": "3.6.13",
"@tarojs/taro-loader": "3.6.13",
"@tarojs/webpack5-runner": "3.6.13",
"@types/react": "^18.0.0",
"@types/webpack-env": "^1.13.6",
"@typescript-eslint/eslint-plugin": "^6.2.0",
"@typescript-eslint/parser": "^6.2.0",
"axios-miniprogram": "latest",
"babel-preset-taro": "3.6.13",
"consola": "^3.2.3",
"eslint": "^8.12.0",
"eslint-config-taro": "3.6.13",
"eslint-plugin-import": "^2.12.0",
"eslint-plugin-react": "^7.8.2",
"eslint-plugin-react-hooks": "^4.2.0",
"postcss": "^8.4.18",
"react": "^18.0.0",
"react-dom": "^18.0.0",
"react-refresh": "^0.11.0",
"stylelint": "^14.4.0",
"tsconfig-paths-webpack-plugin": "^4.0.1",
"typescript": "^5.1.0",
"webpack": "5.78.0"
},
"stackblitz": {
"installDependencies": false,
"startCommand": "pnpm i && pnpm dev:h5"
}
}

View File

@ -1,15 +0,0 @@
{
"miniprogramRoot": "./dist",
"projectname": "taro",
"description": "",
"appid": "touristappid",
"setting": {
"urlCheck": true,
"es6": false,
"enhance": false,
"compileHotReLoad": false,
"postcss": false,
"minified": false
},
"compileType": "miniprogram"
}

View File

@ -1,10 +0,0 @@
{
"miniprogramRoot": "./",
"projectname": "axios-miniprogram",
"appid": "ks739467354825138594",
"libVersion": "0.2.0",
"setting": {
"urlCheck": false
},
"compileType": "miniprogram"
}

View File

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

View File

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

View File

@ -1,5 +0,0 @@
import { PropsWithChildren } from 'react';
export default function App({ children }: PropsWithChildren<any>) {
return children;
}

View File

@ -1,13 +0,0 @@
.page {
padding: 20px;
}
.button {
margin: 20px 0;
}
.code {
padding: 20px;
overflow-x: scroll;
white-space: pre;
}

View File

@ -1,202 +0,0 @@
import { View, Button } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { useEffect, useState } from 'react';
import axios, { createAdapter } from 'axios-miniprogram';
import { consola } from 'consola';
import './home.css';
export default function Home() {
const [config, setConfig] = useState<string>('');
const [response, setResponse] = useState<string>('');
const [error, setError] = useState<string>('');
useEffect(() => {
axios.defaults.adapter = createAdapter({
request: Taro.request,
download: Taro.downloadFile,
upload: Taro.uploadFile,
} as any);
axios.defaults.baseURL = 'https://jsonplaceholder.typicode.com';
axios.defaults.errorHandler = (err) => {
consola.info('[debug err]', (err as any).response);
setError(`<pre>${JSON.stringify(err, null, 2)}</pre>`);
Taro.hideLoading();
Taro.showToast({
icon: 'none',
title: (err as any).response?.data?.errMsg || '未知错误',
});
return Promise.reject(err);
};
axios.use(async (ctx, next) => {
consola.info('[debug req]', ctx.req);
Taro.showLoading({
title: 'Loading...',
});
setConfig(`<pre>${JSON.stringify(ctx.req, null, 2)}</pre>`);
setError('');
setResponse('');
await next();
consola.info('[debug res]', ctx.res);
setResponse(`<pre>${JSON.stringify(ctx.res, null, 2)}</pre>`);
Taro.hideLoading();
});
}, []);
function getRequest() {
axios.get('/users/:id', {
id: 1,
});
}
function postRequest() {
axios.post('/users', {
name: 'Leanne Graham',
username: 'Bret',
email: 'Sincere@april.biz',
address: {
street: 'Kulas Light',
suite: 'Apt. 556',
city: 'Gwenborough',
zipcode: '92998-3874',
geo: { lat: '-37.3159', lng: '81.1496' },
},
phone: '1-770-736-8031 x56442',
website: 'hildegard.org',
company: {
name: 'Romaguera-Crona',
catchPhrase: 'Multi-layered client-server neural-net',
bs: 'harness real-time e-markets',
},
});
}
function putRequest() {
axios.put('/users/:id', {
id: 1,
name: 'Leanne Graham',
username: 'Bret',
email: 'Sincere@april.biz',
address: {
street: 'Kulas Light',
suite: 'Apt. 556',
city: 'Gwenborough',
zipcode: '92998-3874',
geo: { lat: '-37.3159', lng: '81.1496' },
},
phone: '1-770-736-8031 x56442',
website: 'hildegard.org',
company: {
name: 'Romaguera-Crona',
catchPhrase: 'Multi-layered client-server neural-net',
bs: 'harness real-time e-markets',
},
});
}
function deleteRequest() {
axios.delete('/users/:id', {
id: 1,
});
}
function downloadRequest() {
axios.get(
'/users/:id',
{
id: 1,
},
{
download: true,
},
);
}
function uploadRequest() {
Taro.chooseImage({
count: 1,
success({ tempFilePaths }) {
axios.post(
'/users',
{
name: 'filename',
filePath: tempFilePaths[0],
fileType: 'image',
},
{
headers: {
'Content-Type': 'multipart/form-data',
},
upload: true,
},
);
},
});
}
function errorRequest() {
axios.get('/users/:id', {
id: -1,
});
}
function failRequest() {
axios.get(
'/users',
{},
{
timeout: 0,
},
);
}
return (
<View className="page">
<Button className="button" type="primary" onClick={getRequest}>
GET
</Button>
<Button className="button" type="primary" onClick={postRequest}>
POST
</Button>
<Button className="button" type="primary" onClick={putRequest}>
PUT
</Button>
<Button className="button" type="primary" onClick={deleteRequest}>
DELETE
</Button>
<Button className="button" type="primary" onClick={downloadRequest}>
DOWNLOAD
</Button>
<Button className="button" type="primary" onClick={uploadRequest}>
UPLOAD
</Button>
<Button className="button" type="primary" onClick={errorRequest}>
ERROR
</Button>
<Button className="button" type="primary" onClick={failRequest}>
FAIL
</Button>
config:
<View
className="code"
dangerouslySetInnerHTML={{
__html: config,
}}
></View>
response:
<View
className="code"
dangerouslySetInnerHTML={{
__html: response,
}}
></View>
error:
<View
className="code"
dangerouslySetInnerHTML={{
__html: error,
}}
></View>
</View>
);
}

View File

@ -1,17 +0,0 @@
<!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>taro</title>
<script><%= htmlWebpackPlugin.options.script %></script>
</head>
<body>
<div id="app"></div>
</body>
</html>

View File

@ -1,28 +0,0 @@
{
"compilerOptions": {
"target": "es2017",
"module": "commonjs",
"removeComments": false,
"preserveConstEnums": true,
"moduleResolution": "node",
"experimentalDecorators": true,
"noImplicitAny": false,
"allowSyntheticDefaultImports": true,
"outDir": "lib",
"noUnusedLocals": true,
"noUnusedParameters": true,
"strictNullChecks": true,
"sourceMap": true,
"baseUrl": ".",
"rootDir": ".",
"jsx": "preserve",
"allowJs": true,
"resolveJsonModule": true,
"typeRoots": ["node_modules/@types"],
"paths": {
"@/*": ["src/*"]
}
},
"include": ["./src", "./types", "./config"],
"compileOnSave": false
}

View File

@ -1,36 +0,0 @@
/// <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 {
/** NODE 内置环境变量, 会影响到最终构建生成产物 */
NODE_ENV: 'development' | 'production';
/** 当前构建的平台 */
TARO_ENV:
| 'weapp'
| 'swan'
| 'alipay'
| 'h5'
| 'rn'
| 'tt'
| 'quickapp'
| 'qq'
| 'jd';
/**
* appid
* @description env `TARO_APP_ID`便 appid dist/project.config.json
* @see https://taro-docs.jd.com/docs/next/env-mode-config#特殊环境变量-taro_app_id
*/
TARO_APP_ID: string;
}
}

View File

@ -1,2 +0,0 @@
FROM node:16
RUN npm i -g pnpm

View File

@ -1,15 +0,0 @@
{
"setupTasks": [
{
"name": "Install Dependencies",
"command": "pnpm i"
}
],
"tasks": {
"dev": {
"name": "dev",
"command": "pnpm dev:h5",
"runAtStart": true
}
}
}

View File

@ -1,21 +0,0 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
.DS_Store
dist
*.local
# Editor directories and files
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

View File

@ -1,20 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<script>
var coverSupport = 'CSS' in window && typeof CSS.supports === 'function' && (CSS.supports('top: env(a)') ||
CSS.supports('top: constant(a)'))
document.write(
'<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' +
(coverSupport ? ', viewport-fit=cover' : '') + '" />')
</script>
<title></title>
<!--preload-links-->
<!--app-context-->
</head>
<body>
<div id="app"><!--app-html--></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

View File

@ -1,79 +0,0 @@
{
"private": true,
"name": "@examples/uni-app",
"scripts": {
"dev:app": "uni -p app",
"dev:app-android": "uni -p app-android",
"dev:app-ios": "uni -p app-ios",
"dev:custom": "uni -p",
"dev:h5": "uni",
"dev:h5:ssr": "uni --ssr",
"dev:alipay": "uni -p mp-alipay",
"dev:swan": "uni -p mp-baidu",
"dev:jd": "uni -p mp-jd",
"dev:kwai": "uni -p mp-kuaishou",
"dev:lark": "uni -p mp-lark",
"dev:qq": "uni -p mp-qq",
"dev:tt": "uni -p mp-toutiao",
"dev:dd": "uni -p mp-alipay",
"dev:weapp": "uni -p mp-weixin",
"dev:xhs": "uni -p mp-xhs",
"dev:quickapp-webview": "uni -p quickapp-webview",
"dev:quickapp-webview-huawei": "uni -p quickapp-webview-huawei",
"dev:quickapp-webview-union": "uni -p quickapp-webview-union",
"build:app": "uni build -p app",
"build:app-android": "uni build -p app-android",
"build:app-ios": "uni build -p app-ios",
"build:custom": "uni build -p",
"build:h5": "uni build",
"build:h5:ssr": "uni build --ssr",
"build:alipay": "uni build -p mp-alipay",
"build:swan": "uni build -p mp-baidu",
"build:jd": "uni build -p mp-jd",
"build:kwai": "uni build -p mp-kuaishou",
"build:lark": "uni build -p mp-lark",
"build:qq": "uni build -p mp-qq",
"build:tt": "uni build -p mp-toutiao",
"build:dd": "uni -p mp-alipay",
"build:weapp": "uni build -p mp-weixin",
"build:xhs": "uni build -p mp-xhs",
"build:quickapp-webview": "uni build -p quickapp-webview",
"build:quickapp-webview-huawei": "uni build -p quickapp-webview-huawei",
"build:quickapp-webview-union": "uni build -p quickapp-webview-union"
},
"dependencies": {
"@dcloudio/uni-app": "3.0.0-3080720230703001",
"@dcloudio/uni-app-plus": "3.0.0-3080720230703001",
"@dcloudio/uni-components": "3.0.0-3080720230703001",
"@dcloudio/uni-h5": "3.0.0-3080720230703001",
"@dcloudio/uni-mp-alipay": "3.0.0-3080720230703001",
"@dcloudio/uni-mp-baidu": "3.0.0-3080720230703001",
"@dcloudio/uni-mp-jd": "3.0.0-3080720230703001",
"@dcloudio/uni-mp-kuaishou": "3.0.0-3080720230703001",
"@dcloudio/uni-mp-lark": "3.0.0-3080720230703001",
"@dcloudio/uni-mp-qq": "3.0.0-3080720230703001",
"@dcloudio/uni-mp-toutiao": "3.0.0-3080720230703001",
"@dcloudio/uni-mp-weixin": "3.0.0-3080720230703001",
"@dcloudio/uni-mp-xhs": "3.0.0-alpha-3081220230802001",
"@dcloudio/uni-quickapp-webview": "3.0.0-3080720230703001",
"axios-miniprogram": "latest",
"consola": "^2.15.3",
"vue": "^3.2.45",
"vue-i18n": "^9.1.9"
},
"devDependencies": {
"@dcloudio/types": "^3.3.2",
"@dcloudio/uni-automator": "3.0.0-3080720230703001",
"@dcloudio/uni-cli-shared": "3.0.0-3080720230703001",
"@dcloudio/uni-stacktracey": "3.0.0-3080720230703001",
"@dcloudio/vite-plugin-uni": "3.0.0-3080720230703001",
"@vue/tsconfig": "^0.1.3",
"typescript": "^4.9.4",
"vite": "4.0.4",
"vue-tsc": "^1.0.24"
},
"stackblitz": {
"installDependencies": false,
"startCommand": "pnpm i && pnpm dev:h5"
}
}

View File

@ -1,3 +0,0 @@
<template></template>
<script setup lang="ts"></script>
<style></style>

View File

@ -1,8 +0,0 @@
/// <reference types="vite/client" />
declare module '*.vue' {
import { DefineComponent } from 'vue';
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/ban-types
const component: DefineComponent<{}, {}, any>;
export default component;
}

View File

@ -1,207 +0,0 @@
<script lang="ts" setup>
import { ref } from 'vue';
import axios from 'axios-miniprogram';
import consola from 'consola';
const config = ref<string>('');
const response = ref<string>('');
const error = ref<string>('');
axios.defaults.adapter = axios.createAdapter({
request: uni.request as any,
download: uni.downloadFile,
upload: uni.uploadFile as any,
});
axios.defaults.baseURL = 'https://jsonplaceholder.typicode.com';
axios.defaults.errorHandler = (err) => {
consola.info('[debug err]', (err as any).response);
error.value = `<pre>${JSON.stringify(err, null, 2)}</pre>`;
uni.hideLoading();
uni.showToast({
icon: 'none',
title: (err as any).response?.data?.errMsg || '未知错误',
});
return Promise.reject(err);
};
axios.use(async (ctx, next) => {
consola.info('[debug req]', ctx.req);
uni.showLoading({
title: 'Loading...',
});
config.value = `<pre>${JSON.stringify(ctx.req, null, 2)}</pre>`;
error.value = '';
response.value = '';
await next();
consola.info('[debug res]', ctx.res);
response.value = `<pre>${JSON.stringify(ctx.res, null, 2)}</pre>`;
uni.hideLoading();
});
function getRequest() {
axios.get('/users/:id', {
id: 1,
});
}
function postRequest() {
axios.post('/users', {
name: 'Leanne Graham',
username: 'Bret',
email: 'Sincere@april.biz',
address: {
street: 'Kulas Light',
suite: 'Apt. 556',
city: 'Gwenborough',
zipcode: '92998-3874',
geo: { lat: '-37.3159', lng: '81.1496' },
},
phone: '1-770-736-8031 x56442',
website: 'hildegard.org',
company: {
name: 'Romaguera-Crona',
catchPhrase: 'Multi-layered client-server neural-net',
bs: 'harness real-time e-markets',
},
});
}
function putRequest() {
axios.put('/users/:id', {
id: 1,
name: 'Leanne Graham',
username: 'Bret',
email: 'Sincere@april.biz',
address: {
street: 'Kulas Light',
suite: 'Apt. 556',
city: 'Gwenborough',
zipcode: '92998-3874',
geo: { lat: '-37.3159', lng: '81.1496' },
},
phone: '1-770-736-8031 x56442',
website: 'hildegard.org',
company: {
name: 'Romaguera-Crona',
catchPhrase: 'Multi-layered client-server neural-net',
bs: 'harness real-time e-markets',
},
});
}
function deleteRequest() {
axios.delete('/users/:id', {
id: 1,
});
}
function downloadRequest() {
axios.get(
'/users/:id',
{
id: 1,
},
{
download: true,
},
);
}
function uploadRequest() {
uni.chooseImage({
count: 1,
success({ tempFilePaths }) {
axios.post(
'/users',
{
name: 'filename',
filePath: tempFilePaths[0],
fileType: 'image',
},
{
headers: {
'Content-Type': 'multipart/form-data',
},
upload: true,
},
);
},
});
}
function errorRequest() {
axios.get('/users/:id', {
id: -1,
});
}
function failRequest() {
axios.get(
'/users',
{},
{
timeout: 0,
},
);
}
defineExpose({
getRequest,
postRequest,
putRequest,
deleteRequest,
config,
response,
error,
});
</script>
<template>
<view class="page">
<button class="button" type="primary" @click="getRequest">GET </button>
<button class="button" type="primary" @click="postRequest">
POST 请求
</button>
<button class="button" type="primary" @click="putRequest">PUT </button>
<button class="button" type="primary" @click="deleteRequest">
DELETE 请求
</button>
<button class="button" type="primary" @click="downloadRequest">
DOWNLOAD 请求
</button>
<button class="button" type="primary" @click="uploadRequest">
UPLOAD 请求
</button>
<button class="button" type="primary" @click="errorRequest">
ERROR 请求
</button>
<button class="button" type="primary" @click="failRequest">
FAIL 请求
</button>
config:
<view class="code" v-html="config"></view>
response:
<view class="code" v-html="response"></view>
error:
<view class="code" v-html="error"></view>
</view>
</template>
<style>
.page {
padding: 20px;
}
.button {
margin: 20px 0;
}
.code {
padding: 20px;
overflow-x: scroll;
white-space: pre;
}
</style>

View File

@ -1,8 +0,0 @@
import { createSSRApp } from 'vue';
import App from './App.vue';
export function createApp() {
const app = createSSRApp(App);
return {
app,
};
}

View File

@ -1,72 +0,0 @@
{
"name": "",
"appid": "",
"description": "",
"versionName": "1.0.0",
"versionCode": "100",
"transformPx": false,
/* 5+App */
"app-plus": {
"usingComponents": true,
"nvueStyleCompiler": "uni-app",
"compilerVersion": 3,
"splashscreen": {
"alwaysShowBeforeRender": true,
"waiting": true,
"autoclose": true,
"delay": 0
},
/* */
"modules": {},
/* */
"distribute": {
/* android */
"android": {
"permissions": [
"<uses-permission android:name=\"android.permission.CHANGE_NETWORK_STATE\"/>",
"<uses-permission android:name=\"android.permission.MOUNT_UNMOUNT_FILESYSTEMS\"/>",
"<uses-permission android:name=\"android.permission.VIBRATE\"/>",
"<uses-permission android:name=\"android.permission.READ_LOGS\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_WIFI_STATE\"/>",
"<uses-feature android:name=\"android.hardware.camera.autofocus\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\"/>",
"<uses-permission android:name=\"android.permission.CAMERA\"/>",
"<uses-permission android:name=\"android.permission.GET_ACCOUNTS\"/>",
"<uses-permission android:name=\"android.permission.READ_PHONE_STATE\"/>",
"<uses-permission android:name=\"android.permission.CHANGE_WIFI_STATE\"/>",
"<uses-permission android:name=\"android.permission.WAKE_LOCK\"/>",
"<uses-permission android:name=\"android.permission.FLASHLIGHT\"/>",
"<uses-feature android:name=\"android.hardware.camera\"/>",
"<uses-permission android:name=\"android.permission.WRITE_SETTINGS\"/>"
]
},
/* ios */
"ios": {},
/* SDK */
"sdkConfigs": {}
}
},
/* */
"quickapp": {},
/* */
"mp-weixin": {
"appid": "",
"setting": {
"urlCheck": false
},
"usingComponents": true
},
"mp-alipay": {
"usingComponents": true
},
"mp-baidu": {
"usingComponents": true
},
"mp-toutiao": {
"usingComponents": true
},
"uniStatistics": {
"enable": false
},
"vueVersion": "3"
}

View File

@ -1,9 +0,0 @@
{
"pages": [{ "path": "home", "style": {} }],
"globalStyle": {
"backgroundTextStyle": "light",
"navigationBarBackgroundColor": "#fff",
"navigationBarTitleText": "axios-miniprogram",
"navigationBarTextStyle": "black"
}
}

View File

@ -1,6 +0,0 @@
export {};
declare module 'vue' {
type Hooks = App.AppInstance & Page.PageInstance;
type ComponentCustomOptions = Hooks;
}

View File

@ -1,13 +0,0 @@
{
"extends": "@vue/tsconfig/tsconfig.json",
"compilerOptions": {
"sourceMap": true,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
},
"lib": ["esnext", "dom"],
"types": ["@dcloudio/types"]
},
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
}

View File

@ -1,10 +0,0 @@
import { defineConfig } from 'vite';
import uni from '@dcloudio/vite-plugin-uni';
// https://vitejs.dev/config/
export default defineConfig({
server: {
port: 3000,
},
plugins: [uni()],
});

View File

@ -1,3 +1,4 @@
declare const uni: any;
declare const wx: any;
declare const my: any;
declare const swan: any;
@ -7,4 +8,3 @@ declare const qh: any;
declare const ks: any;
declare const dd: any;
declare const jd: any;
declare const xhs: any;

View File

@ -1,87 +1,85 @@
{
"name": "axios-miniprogram",
"version": "2.7.2",
"version": "2.2.0",
"description": "基于 Promise 的 HTTP 请求库,适用于各大小程序平台。",
"main": "dist/axios-miniprogram.cjs.js",
"module": "dist/axios-miniprogram.esm.js",
"types": "dist/axios-miniprogram.d.ts",
"type": "module",
"files": [
"dist"
],
"repository": {
"type": "git",
"url": "git+https://github.com/zjxxxxxxxxx/axios-miniprogram.git"
"url": "git+https://github.com/zjx0905/axios-miniprogram.git"
},
"keywords": [
"axios",
"miniprogram",
"request",
"mini",
"miniprogram"
"promise",
"alipay",
"uni-app",
"wechat",
"fetch",
"network"
],
"author": "zjxxxxxxxxx <954270063@qq.com>",
"author": "zjx0905 <954270063@qq.com>",
"bugs": {
"url": "https://github.com/zjxxxxxxxxx/axios-miniprogram/issues"
"url": "https://github.com/zjx0905/axios-miniprogram/issues"
},
"homepage": "https://axios-miniprogram.com",
"license": "MIT",
"type": "module",
"engines": {
"node": ">=16",
"pnpm": ">=8"
},
"scripts": {
"cz": "simple-git-hooks && czg",
"play": "esno scripts/play.ts",
"typecheck": "tsc --noEmit",
"lint": "eslint --cache . --fix",
"format": "prettier -w {src,test,scripts}/**/*.{ts,tsx,js,jsx}",
"cz": "czg",
"build": "esno scripts/build.ts",
"build:assets": "esno scripts/build.assets.ts",
"dev": "pnpm build -a -w",
"build:asset": "esno scripts/build-asset.ts",
"watch": "pnpm build -a -w",
"release": "esno scripts/release.ts",
"publish:ci": "esno scripts/publish.ts",
"changelog": "conventional-changelog -p angular -i CHANGELOG.md -s",
"releaselog": "esno scripts/releaselog.ts",
"upload:asset": "esno scripts/upload-asset.ts",
"test": "vitest run",
"test:watch": "vitest",
"test:cov": "vitest run --coverage",
"docs:dev": "pnpm --filter docs dev",
"docs:build": "pnpm --filter docs build",
"docs:preview": "pnpm --filter docs preview",
"docs:deploy": "esno scripts/docs.deploy.ts"
"typecheck": "tsc --noEmit",
"lint": "eslint --cache .",
"lint:fix": "pnpm lint --fix",
"docs:dev": "pnpm -C docs dev",
"docs:build": "pnpm -C docs build",
"docs:preview": "pnpm -C docs preview",
"postinstall": "simple-git-hooks"
},
"devDependencies": {
"@commitlint/cli": "^17.7.1",
"@commitlint/config-conventional": "^17.7.0",
"@rollup/plugin-typescript": "^11.1.2",
"@types/minimist": "^1.2.2",
"@types/node": "^18.17.5",
"@types/semver": "^7.5.0",
"@typescript-eslint/eslint-plugin": "^5.62.0",
"@typescript-eslint/parser": "^5.62.0",
"@vitest/coverage-istanbul": "^0.30.1",
"chalk": "^5.3.0",
"@commitlint/cli": "^17.4.4",
"@commitlint/config-conventional": "^17.4.4",
"@types/node": "^18.15.5",
"@typescript-eslint/eslint-plugin": "^5.55.0",
"@typescript-eslint/parser": "^5.55.0",
"@vitest/coverage-istanbul": "^0.30.0",
"actions-toolkit": "^6.0.1",
"chalk": "^5.2.0",
"consola": "^2.15.3",
"conventional-changelog-cli": "^2.2.2",
"cz-git": "1.3.8",
"czg": "1.3.8",
"enquirer": "^2.4.1",
"eslint": "^8.47.0",
"enquirer": "^2.3.6",
"eslint": "^8.36.0",
"esno": "^0.16.3",
"fast-glob": "^3.3.1",
"fast-glob": "^3.2.12",
"jszip": "^3.10.1",
"lint-staged": "13.2.0",
"minimist": "^1.2.8",
"prettier": "2.8.5",
"rimraf": "^4.4.1",
"rollup": "^3.28.0",
"rollup-plugin-dts": "^5.3.1",
"rimraf": "^4.4.0",
"rollup": "^3.20.0",
"rollup-plugin-dts": "^5.3.0",
"rollup-plugin-esbuild": "^5.0.0",
"semver": "^7.5.4",
"simple-git-hooks": "^2.9.0",
"tslib": "^2.6.1",
"typescript": "^5.1.6",
"vitest": "^0.30.1"
"semver": "^7.3.8",
"simple-git-hooks": "^2.8.1",
"typescript": "^5.0.2",
"vitest": "^0.30.0"
},
"simple-git-hooks": {
"pre-commit": "pnpm lint-staged && pnpm test && pnpm build -a",
@ -96,7 +94,7 @@
"*.{js,json}": [
"prettier --write"
],
"*.ts": [
"*.ts?(x)": [
"eslint",
"prettier --parser=typescript --write"
]
@ -105,9 +103,7 @@
"peerDependencyRules": {
"ignoreMissing": [
"@algolia/client-search",
"esbuild",
"vite",
"eslint"
"esbuild"
]
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,3 +1,2 @@
packages:
- docs
- examples/*

View File

@ -1,8 +1,7 @@
import { readFileSync } from 'node:fs';
import { RollupOptions, OutputOptions, Plugin, ModuleFormat } from 'rollup';
import esbuildPlugin from 'rollup-plugin-esbuild';
import dtsPlugin from 'rollup-plugin-dts';
import { __dirname, distPath, getPkgJSON, resolve } from './scripts/utils';
import { __dirname, distPath, getPkgJSON, resolve } from './scripts/utils.js';
const pkg = getPkgJSON();
const inputPath = resolve('src/index.ts');
@ -20,50 +19,45 @@ function main() {
return configs;
}
function buildConfig(format: ModuleFormat | 'dts'): RollupOptions {
function buildConfig(format) {
const isDts = format === 'dts';
const output: OutputOptions = {
const output = {
file: resolveOutput(format, isDts),
format: isDts ? 'es' : format,
name: pkg.name,
exports: 'named',
exports: 'default',
indent: false,
sourcemap: isDts ? false : sourceMap,
};
const plugins: Plugin[] = [];
if (isDts) {
plugins.push(
dtsPlugin({
tsconfig: resolve('tsconfig.json'),
}),
patchTypePlugin([resolve('global.d.ts')]),
);
} else {
plugins.push(
esbuildPlugin({
tsconfig: resolve('tsconfig.json'),
sourceMap: output.sourcemap as boolean,
target: 'es2015',
minify: true,
}),
);
}
return {
input: inputPath,
output,
plugins,
plugins: [
isDts
? [
dtsPlugin({
tsconfig: resolve('tsconfig.json'),
}),
compleTypePlugin([resolve('global.d.ts')]),
]
: esbuildPlugin({
tsconfig: resolve('tsconfig.json'),
sourceMap: output.sourcemap,
target: 'es2015',
minify: true,
}),
],
};
}
function resolveOutput(format: string, isDts?: boolean) {
function resolveOutput(format, isDts) {
return resolve(distPath, `${pkg.name}${isDts ? '.d.ts' : `.${format}.js`}`);
}
function patchTypePlugin(files: string[]): Plugin {
function compleTypePlugin(files) {
return {
name: 'patch-type',
name: 'comple-type',
renderChunk: (code) =>
`${files
.map(

View File

@ -1,35 +1,31 @@
import fs from 'node:fs';
import { basename } from 'node:path';
import fg from 'fast-glob';
import JSZip from 'jszip';
import consola from 'consola';
import chalk from 'chalk';
import { distPath, exec } from './utils';
import { checkSize } from './checkSize';
import { distPath, exec, getFileName } from './utils';
main();
async function main() {
exec('pnpm build');
console.log('');
consola.info('Generate assets\n');
consola.info('Generate asset\n');
for (const filePath of await fg(`${distPath}/**.js`)) {
await generateZip(filePath, filePath.replace(/\.js$/, '.zip'));
}
checkSize(`${distPath}/**.zip`);
}
function generateZip(inputPath: string, outputPath: string) {
const start = Date.now();
const inputName = basename(inputPath);
const outputName = basename(outputPath);
const inputName = getFileName(inputPath);
const outputName = getFileName(outputPath);
console.log(chalk.cyanBright.bold(`${inputPath} → dist/${outputName}...`));
return new Promise((resolve, reject) => {
const finish = (result: any) => {
const finish = (result) => {
console.log(
`${chalk.green('created')} ${chalk.greenBright.bold(
`dist/${outputName} in ${Date.now() - start}ms\n`,

View File

@ -1,9 +1,6 @@
import minimist from 'minimist';
import consola from 'consola';
import { distPath, exec } from './utils';
import { checkSize } from './checkSize';
import { safeExit } from './utils';
import { exec } from './utils';
const args = minimist(process.argv.slice(2));
const watch = Boolean(args.watch || args.w);
@ -17,17 +14,15 @@ function main() {
exec('rimraf dist');
consola.info('Rollup');
safeExit(() => {
try {
exec(
`rollup -c rollup.config.ts --configPlugin typescript ${
`rollup -c ${
watch ? '-w' : ''
} --environment SOURCE_MAP:${sourceMap},DTS:${dts}`,
);
});
if (!watch) {
checkSize(`${distPath}/**.js`);
} catch {
consola.error('已退出');
process.exit();
}
console.info('\n');

View File

@ -1,20 +0,0 @@
import { readFileSync } from 'node:fs';
import { gzipSync } from 'node:zlib';
import { basename } from 'node:path';
import fg from 'fast-glob';
import chalk from 'chalk';
export async function checkSize(source: string) {
for (const filePath of await fg(source)) {
const file = readFileSync(filePath);
const minSize = (file.length / 1024).toFixed(2) + 'kb';
const gzipped = gzipSync(file);
const gzippedSize = (gzipped.length / 1024).toFixed(2) + 'kb';
console.log(
`${chalk.gray(
chalk.bold(basename(filePath)),
)} min:${minSize} / gzip:${gzippedSize}`,
);
}
}

View File

@ -1,27 +0,0 @@
import consola from 'consola';
import { exec } from './utils';
main();
function main() {
consola.info('Clean');
const exist = exec('git branch --list docs', {
stdio: 'pipe',
})
.toString()
.trim();
if (exist) {
exec('git branch -D docs');
}
console.log('');
consola.info('Check build');
exec('pnpm docs:build');
console.log('');
consola.info('Git branch docs\n');
exec('git branch docs');
consola.info('Git push docs\n');
exec('git push origin docs -f');
}

View File

@ -1,48 +0,0 @@
import enquirer from 'enquirer';
import consola from 'consola';
import { exec, resolve, safeExit } from './utils';
import { readdirSync } from 'fs';
safeExit(main);
async function main() {
const { framework } = await enquirer.prompt<{ framework: string }>({
type: 'select',
name: 'framework',
message: '请选择跨端框架',
choices: readdirSync(resolve('examples')).filter((i) => i !== '.DS_Store'),
});
const metas = framework === 'taro' ? taroMetas() : uniAppMetas();
const { platform } = await enquirer.prompt<{ platform: string }>({
type: 'select',
name: 'platform',
message: '请选择启动平台',
choices: metas,
});
console.log();
consola.info(
`启动${metas.find((meta) => meta.name === platform)!.message}...`,
);
exec(`pnpm --filter @examples/${framework} dev:${platform}`);
}
function taroMetas() {
return [
{ name: 'h5', message: 'H5' },
{ name: 'weapp', message: '微信小程序' },
{ name: 'swan', message: '百度小程序' },
{ name: 'alipay', message: '支付宝小程序' },
{ name: 'tt', message: '抖音小程序' },
{ name: 'qq', message: 'QQ 小程序' },
{ name: 'jd', message: '京东小程序' },
{ name: 'dd', message: '钉钉小程序' },
{ name: 'lark', message: '飞书小程序' },
{ name: 'kwai', message: '快手小程序' },
];
}
function uniAppMetas() {
return [...taroMetas(), { name: 'xhs', message: '小红书小程序' }];
}

View File

@ -22,7 +22,7 @@ function main() {
}
function generatePublishPkg() {
const publishPkg: AnyObject = {};
const publishPkg = {};
[
'name',

View File

@ -1,11 +1,10 @@
import { writeFileSync } from 'node:fs';
import semver, { ReleaseType } from 'semver';
import fs from 'node:fs';
import semver from 'semver';
import enquirer from 'enquirer';
import consola from 'consola';
import { exec, pkgPath, getPkgJSON, resolve } from './utils';
import { exec, pkgPath, getPkgJSON } from './utils';
const pkg = getPkgJSON();
const versionTSPath = resolve('src/version.ts');
const { version: currentVersion } = pkg;
main().catch((err) => exit(err.message));
@ -27,10 +26,10 @@ async function main() {
exec(`git tag -a v${version} -m "v${version}"`);
consola.info('Git push');
exec('git push -f');
exec('git push');
consola.info('Git push tag');
exec(`git push -f origin v${version}`);
exec(`git push origin v${version}`);
}
function checkBranch() {
@ -103,9 +102,7 @@ function createReleases() {
];
const releases: string[] = [];
for (const [type, preid] of types) {
releases.push(
`${type} (${semver.inc(currentVersion, type as ReleaseType, preid)})`,
);
releases.push(`${type} (${semver.inc(currentVersion, type, preid)})`);
}
return releases;
}
@ -118,7 +115,5 @@ function exit(msg: string) {
function updateVersion(version: string) {
pkg.version = version;
writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n');
writeFileSync(versionTSPath, `export const version = '${version}';`);
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n');
}

View File

@ -5,7 +5,7 @@ import { getPkgJSON, resolve } from './utils';
const changelogPath = resolve('CHANGELOG.md');
const releaselogPath = resolve('RELEASELOG.md');
const { version } = getPkgJSON();
const versionRE = new RegExp(`^#{1,2} \\[?${version}\\]?\\(?`);
const versionRE = new RegExp(`^# \\[?${version}\\]?[ (]`);
main();
@ -17,7 +17,7 @@ async function main() {
let releaselog = '';
for await (const line of changelog) {
if (/^#{1,2} /.test(line) && !versionRE.test(line)) {
if (line.startsWith('# ') && !versionRE.test(line)) {
break;
}
releaselog += `${line}\n`;

View File

@ -1,10 +1,4 @@
import { test } from 'vitest';
import {
PLAIN_METHODS,
WITH_PARAMS_METHODS,
WITH_DATA_METHODS,
} from '@/constants/methods';
import { AxiosAdapterRequestConfig } from '@/adpater/createAdapter';
import { AxiosAdapterRequestConfig } from 'src';
export function asyncNext() {
return Promise.resolve().then;
@ -23,17 +17,26 @@ export function captureError<T = any>(fn: () => void) {
}
}
export function checkStack(error: Error) {
if (error.stack) {
return error.stack.indexOf('at') === error.stack.indexOf('at /');
}
return true;
}
export function noop() {
return;
}
export function mockResponse(
status = 200,
headers: AnyObject = {},
data: AnyObject = {},
status: number,
statusText: string,
headers: AnyObject,
data: AnyObject,
) {
return {
status,
statusText,
headers,
data,
};
@ -70,13 +73,13 @@ function mockAdapterBase(
if (!canceled) {
switch (type) {
case 'success':
config.success(mockResponse(200, headers, data));
config.success(mockResponse(200, 'OK', headers, data));
break;
case 'error':
config.success(mockResponse(500, headers, data));
config.success(mockResponse(500, 'ERROR', headers, data));
break;
case 'fail':
config.fail(mockResponse(400, headers, data));
config.fail(mockResponse(400, 'FAIL', headers, data));
break;
}
@ -103,15 +106,3 @@ export function mockAdapterError(options: MockAdapterOptions = {}) {
export function mockAdapterFail(options: MockAdapterOptions = {}) {
return mockAdapterBase('fail', options);
}
export const methods = [
...PLAIN_METHODS,
...WITH_PARAMS_METHODS,
...WITH_DATA_METHODS,
];
export const testEachMethods = test.each(methods);
export function eachMethods(cb: (k: (typeof methods)[number]) => void) {
methods.forEach(cb);
}

27
scripts/upload-asset.ts Normal file
View File

@ -0,0 +1,27 @@
import fs from 'node:fs';
import fg from 'fast-glob';
import { Toolkit } from 'actions-toolkit';
import consola from 'consola';
import { distPath, getFileName } from './utils';
const { UPLOAD_URL, RELEASE_ID } = process.env;
const toolkit = new Toolkit();
main();
async function main() {
consola.info('Upload asset\n');
for (const filePath of await fg(`${distPath}/**.zip`)) {
await toolkit.github.repos.uploadReleaseAsset({
...toolkit.context.repo,
url: UPLOAD_URL,
headers: {
'content-type': 'application/zip',
'content-length': fs.statSync(filePath).size,
},
name: getFileName(filePath),
release_id: Number(RELEASE_ID),
data: fs.readFileSync(filePath) as unknown as string,
});
}
}

15
scripts/utils.js Normal file
View File

@ -0,0 +1,15 @@
import path from 'node:path';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
import { execSync } from 'node:child_process';
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) => path.resolve(__dirname, ...paths);
export const exec = (command, options) =>
execSync(command, { stdio: 'inherit', ...(options ?? {}) });
export const getPkgJSON = () => require(pkgPath);
export const getFileName = (filePath) => filePath.match(/\/([^/]*)$/)[1];

View File

@ -1,40 +0,0 @@
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 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 function safeExit(run: () => unknown) {
try {
const p = run();
if (isPromise(p)) {
return p.catch(exit);
}
} catch {
exit();
}
}
function exit() {
consola.error('已退出');
process.exit();
}

347
src/adapter.ts Normal file
View File

@ -0,0 +1,347 @@
import {
isFunction,
isPlainObject,
isString,
isUndefined,
} from './helpers/isTypes';
import { assert } from './helpers/error';
import {
AxiosProgressCallback,
AxiosRequestFormData,
AxiosRequestHeaders,
} from './core/Axios';
export type AxiosAdapterRequestType = 'request' | 'download' | 'upload';
export type AxiosAdapterRequestMethod =
| 'OPTIONS'
| 'GET'
| 'HEAD'
| 'POST'
| 'PUT'
| 'PATCH'
| 'DELETE'
| 'TRACE'
| 'CONNECT';
export type AxiosAdapterResponseData = string | ArrayBuffer | AnyObject;
export interface AxiosAdapterResponse extends AnyObject {
/**
*
*/
status: number;
/**
*
*/
statusText: string;
/**
*
*/
headers: AnyObject;
/**
*
*/
data: AxiosAdapterResponseData;
}
export interface AxiosAdapterResponseError extends AnyObject {
/**
*
*/
status: number;
/**
*
*/
statusText: string;
/**
*
*/
headers: AnyObject;
/**
*
*/
data?: AnyObject;
}
export interface AxiosAdapterRequestConfig extends AnyObject {
/**
*
*/
type: 'request' | 'upload' | 'download';
/**
*
*/
url: string;
/**
* HTTP
*/
method: AxiosAdapterRequestMethod;
/**
*
*/
params?: AnyObject;
/**
*
*/
data?: AnyObject;
/**
*
*/
headers?: AnyObject;
/**
*
*/
dataType?: 'json' | '其他';
/**
*
*/
responseType?: 'text' | 'arraybuffer';
/**
* 60000
*/
timeout?: number;
/**
*
*/
success(response: AxiosAdapterResponse): void;
/**
*
*/
fail(error: AxiosAdapterResponseError): void;
}
export interface AxiosAdapterBaseOptions extends AxiosAdapterRequestConfig {
header?: AxiosRequestHeaders;
success(response: AxiosAdapterResponse): void;
fail(error: AxiosAdapterResponseError): void;
}
export interface AxiosAdapterUploadOptions
extends AxiosAdapterBaseOptions,
AxiosRequestFormData {
fileName: string;
formData?: AnyObject;
}
export interface AxiosAdapterDownloadOptions extends AxiosAdapterBaseOptions {
filePath?: string;
}
export interface AxiosAdapterRequest {
(config: AxiosAdapterBaseOptions): AxiosAdapterTask;
}
export interface AxiosAdapterUpload {
(config: AxiosAdapterUploadOptions): AxiosAdapterTask;
}
export interface AxiosAdapterDownload {
(config: AxiosAdapterDownloadOptions): AxiosAdapterTask;
}
export interface AxiosPlatform {
request: AxiosAdapterRequest;
upload: AxiosAdapterUpload;
download: AxiosAdapterDownload;
}
export type AxiosAdapterTask =
| undefined
| void
| {
abort?(): void;
onProgressUpdate?(callback: AxiosProgressCallback): void;
offProgressUpdate?(callback: AxiosProgressCallback): void;
};
export interface AxiosAdapter {
(config: AxiosAdapterRequestConfig): AxiosAdapterTask;
}
export function getAdapterDefault() {
const platform = revisePlatformApiNames(getPlatform());
function getPlatform() {
const undef = 'undefined';
if (typeof uni !== undef) {
return {
request: uni.request,
uploadFile: uni.uploadFile,
downloadFile: uni.downloadFile,
};
} else if (typeof wx !== undef) {
return wx;
} else if (typeof my !== undef) {
return my;
} else if (typeof swan !== undef) {
return swan;
} else if (typeof tt !== undef) {
return tt;
} else if (typeof qq !== undef) {
return qq;
} else if (typeof qh !== undef) {
return qh;
} else if (typeof ks !== undef) {
return ks;
} else if (typeof dd !== undef) {
return dd;
} else if (typeof jd !== undef) {
return jd;
}
}
function revisePlatformApiNames(platform?: AnyObject) {
return (
platform && {
request: platform.request ?? platform.httpRequest,
upload: platform.upload ?? platform.uploadFile,
download: platform.download ?? platform.downloadFile,
}
);
}
if (!isPlatform(platform)) {
return;
}
return createAdapter(platform);
}
export function createAdapter(platform: AxiosPlatform) {
assert(isPlainObject(platform), 'platform 不是一个 object');
assert(isFunction(platform.request), 'request 不是一个 function');
assert(isFunction(platform.upload), 'upload 不是一个 function');
assert(isFunction(platform.download), 'download 不是一个 function');
function adapter(config: AxiosAdapterRequestConfig): AxiosAdapterTask {
const baseOptions = transformOptions(config);
switch (config.type) {
case 'request':
return processRequest(platform.request, baseOptions);
case 'upload':
return processUpload(platform.upload, baseOptions);
case 'download':
return processDownload(platform.download, baseOptions);
}
}
function processRequest(
request: AxiosAdapterRequest,
baseOptions: AxiosAdapterBaseOptions,
): AxiosAdapterTask {
return request(baseOptions);
}
function processUpload(
upload: AxiosAdapterUpload,
baseOptions: AxiosAdapterBaseOptions,
): AxiosAdapterTask {
const { name, filePath, fileType, ...formData } =
baseOptions.data as AxiosRequestFormData;
const options = {
...baseOptions,
name,
/**
* [ fileName name](https://open.dingtalk.com/document/orgapp/dd-upload-objects#title-ngk-rr1-eow)
*/
fileName: name,
filePath,
/**
* |
*/
fileType,
formData,
};
return upload(options);
}
function processDownload(
download: AxiosAdapterDownload,
baseOptions: AxiosAdapterBaseOptions,
): AxiosAdapterTask {
const options: AxiosAdapterDownloadOptions = {
...baseOptions,
filePath: baseOptions.params?.filePath,
success(response): void {
injectDownloadData(response);
baseOptions.success(response);
},
};
return download(options);
}
function transformResponse(response: AnyObject): void {
response.status = response.status ?? response.statusCode;
response.statusText = 'OK';
if (isUndefined(response.status)) {
response.status = 400;
response.statusText = 'Fail Adapter';
}
response.headers = response.headers ?? response.header ?? {};
if (isUndefined(response.data) && isString(response.errMsg)) {
response.data = {
errMsg: response.errMsg,
errno: response.errno,
};
}
cleanResponse(response, ['statusCode', 'errMsg', 'errno', 'header']);
}
function transformOptions(
config: AxiosAdapterRequestConfig,
): AxiosAdapterBaseOptions {
return {
...config,
header: config.headers,
success(response): void {
transformResponse(response);
config.success(response);
},
fail(error: AxiosAdapterResponseError): void {
transformResponse(error);
config.fail(error);
},
};
}
function injectDownloadData(response: AnyObject): void {
response.data = {
filePath: response.filePath,
tempFilePath:
response.tempFilePath ||
// response.apFilePath 为支付宝小程序基础库小于 2.7.23 的特有属性。
response.apFilePath,
};
cleanResponse(response, ['tempFilePath', 'apFilePath', 'filePath']);
}
/**
* response key
*/
function cleanResponse(response: AnyObject, keys: string[]) {
for (const key of keys) {
delete response[key];
}
}
return adapter;
}
export function isPlatform(value: unknown): value is AxiosPlatform {
return (
isPlainObject(value) &&
isFunction(value.request) &&
isFunction(value.upload) &&
isFunction(value.download)
);
}

View File

@ -1,394 +0,0 @@
import { isFunction, isPlainObject } from '../helpers/types';
import { assert } from '../helpers/error';
import { ignore, orgIgnore } from '../helpers/ignore';
import {
AxiosProgressEvent,
AxiosRequestFormData,
AxiosRequestHeaders,
} from '../core/Axios';
/**
*
*/
export type AxiosAdapterRequestType = 'request' | 'download' | 'upload';
/**
*
*/
export type AxiosAdapterRequestMethod =
| 'OPTIONS'
| 'GET'
| 'HEAD'
| 'POST'
| 'PUT'
| 'PATCH'
| 'DELETE'
| 'TRACE'
| 'CONNECT';
/**
*
*/
export type AxiosAdapterRequestData = string | AnyObject | ArrayBuffer;
/**
*
*/
export type AxiosAdapterResponseData = string | ArrayBuffer | AnyObject;
/**
*
*/
export interface AxiosAdapterResponse extends AnyObject {
/**
*
*/
status?: number;
/**
*
*/
headers?: AnyObject;
/**
*
*/
data: AxiosAdapterResponseData;
}
/**
*
*/
export interface AxiosAdapterResponseError extends AnyObject {
/**
*
*/
status?: number;
/**
*
*/
headers?: AnyObject;
/**
*
*/
data?: AnyObject;
}
/**
*
*/
export interface AxiosAdapterRequestConfig extends AnyObject {
/**
*
*/
type: 'request' | 'upload' | 'download';
/**
*
*/
url: string;
/**
* HTTP
*/
method: AxiosAdapterRequestMethod;
/**
*
*/
params?: AnyObject;
/**
*
*/
data?: AxiosAdapterRequestData;
/**
*
*/
headers?: AnyObject;
/**
*
*/
dataType?: string;
/**
*
*/
responseType?: string;
/**
* 60000
*/
timeout?: number;
/**
*
*/
success(response: AxiosAdapterResponse): void;
/**
*
*/
fail(error: AxiosAdapterResponseError): void;
}
/**
*
*/
export interface AxiosAdapterBaseOptions extends AxiosAdapterRequestConfig {
/**
* headers
*/
header?: AxiosRequestHeaders;
/**
*
*/
success(response: AnyObject): void;
/**
*
*/
fail(error: AnyObject): void;
}
/**
*
*/
export type AxiosAdapterRequestOptions = AxiosAdapterBaseOptions;
/**
*
*/
export interface AxiosAdapterDownloadOptions extends AxiosAdapterBaseOptions {
/**
*
*/
filePath?: string;
}
/**
*
*/
export interface AxiosAdapterUploadOptions
extends AxiosAdapterBaseOptions,
AxiosRequestFormData {
/**
* [ fileName name](https://open.dingtalk.com/document/orgapp/dd-upload-objects#title-ngk-rr1-eow)
*/
fileName: string;
/**
* |
*/
fileType?: 'image' | 'video' | 'audie';
/**
*
*/
formData?: AnyObject;
}
/**
*
*/
export interface AxiosAdapterRequest {
(config: AxiosAdapterRequestOptions): AxiosAdapterPlatformTask;
}
/**
*
*/
export interface AxiosAdapterDownload {
(config: AxiosAdapterDownloadOptions): AxiosAdapterPlatformTask;
}
/**
*
*/
export interface AxiosAdapterUpload {
(config: AxiosAdapterUploadOptions): AxiosAdapterPlatformTask;
}
/**
*
*/
export interface AxiosAdapterPlatform {
/**
*
*/
request: AxiosAdapterRequest;
/**
*
*/
download: AxiosAdapterDownload;
/**
*
*/
upload: AxiosAdapterUpload;
}
/**
*
*/
export type AxiosAdapterPlatformTask =
| undefined
| void
| {
abort?(): void;
onProgressUpdate?(callback: (event: AxiosProgressEvent) => void): void;
offProgressUpdate?(callback: (event: AxiosProgressEvent) => void): void;
};
/**
*
*/
export interface AxiosAdapter {
(config: AxiosAdapterRequestConfig): AxiosAdapterPlatformTask;
}
/**
*
*
* @param platform API
*/
export function createAdapter(platform: AxiosAdapterPlatform) {
assert(isPlainObject(platform), 'platform 不是一个 object');
assert(isFunction(platform.request), 'request 不是一个 function');
assert(isFunction(platform.upload), 'upload 不是一个 function');
assert(isFunction(platform.download), 'download 不是一个 function');
function adapter(
config: AxiosAdapterRequestConfig,
): AxiosAdapterPlatformTask {
const options = transformOptions(config);
switch (config.type) {
case 'request':
return processRequest(platform.request, options);
case 'download':
return processDownload(platform.download, options);
case 'upload':
return processUpload(platform.upload, options);
}
}
function transformOptions(
config: AxiosAdapterRequestConfig,
): AxiosAdapterBaseOptions {
const { success, fail } = config;
return {
...config,
header: config.headers,
success(rawRes: AxiosAdapterResponse) {
const response = transformResponse(rawRes) as AxiosAdapterResponse;
success(response);
},
fail(rawErr: AxiosAdapterResponseError) {
const responseError = {
...transformResponse(rawErr),
data: {
errno:
// 微信 | 飞书新规范
rawErr.errno ??
// 支付宝 | 钉钉
rawErr.error ??
// 百度 | 360 | 飞书
rawErr.errCode ??
// 抖音
rawErr.errNo,
errMsg:
// 飞书新规范
rawErr.errString ??
// 微信 | 支付宝 | 百度 | 抖音 | QQ | 360 | 飞书
rawErr.errMsg ??
// 钉钉
rawErr.errorMessage,
},
};
fail(responseError);
},
};
}
function transformResponse(
rawRes: AxiosAdapterResponse | AxiosAdapterResponseError,
) {
return {
...ignore(
rawRes,
'statusCode',
'header',
// 错误码
'errno',
'error',
'errCode',
'errNo',
// 错误消息
'errMsg',
'errorMessage',
'errString',
),
status: rawRes.status ?? rawRes.statusCode,
headers: rawRes.headers ?? rawRes.header,
};
}
function processRequest(
request: AxiosAdapterRequest,
rawOpts: AxiosAdapterBaseOptions,
): AxiosAdapterPlatformTask {
return request(rawOpts);
}
function processDownload(
download: AxiosAdapterDownload,
rawOpts: AxiosAdapterBaseOptions,
): AxiosAdapterPlatformTask {
const options = rawOpts as AxiosAdapterDownloadOptions;
const { params, success } = options;
options.filePath = params?.filePath;
options.success = (rawRes) => {
const response = {
...ignore(rawRes, 'tempFilePath', 'apFilePath', 'filePath', 'fileSize'),
data: {
filePath: rawRes.filePath,
tempFilePath:
rawRes.tempFilePath ??
// 支付宝
rawRes.apFilePath,
fileSize:
// 飞书
rawRes.fileSize,
},
};
success(response);
};
orgIgnore(options, ['params']);
return download(options);
}
function processUpload(
upload: AxiosAdapterUpload,
rawOpts: AxiosAdapterBaseOptions,
): AxiosAdapterPlatformTask {
const options = rawOpts as AxiosAdapterUploadOptions;
const { data, success } = options;
const { name, filePath, fileType, ...formData } = data as AnyObject;
options.name = name;
options.filePath = filePath;
options.formData = formData;
// 支付宝 | 钉钉
options.fileName = name;
// 支付宝 | 钉钉
options.fileType = fileType;
options.success = (rawRes) => {
const response = { ...rawRes };
if (options.responseType === 'text' && options.dataType === 'json') {
try {
response.data = JSON.parse(rawRes.data);
} catch {
//
}
}
success(response);
};
orgIgnore(options, ['params', 'data']);
return upload(options);
}
return adapter;
}

View File

@ -1,76 +0,0 @@
import { isFunction, isPlainObject } from '../helpers/types';
import { AxiosAdapterPlatform, createAdapter } from './createAdapter';
/**
*
*/
export function getDefaultAdapter() {
const platform = revisePlatformApiNames(getPlatform());
if (isPlatform(platform)) {
return createAdapter(platform);
}
}
function getPlatform() {
const undef = 'undefined';
// 微信小程序
if (typeof wx !== undef) {
return wx;
}
// 支付宝小程序
else if (typeof my !== undef) {
return my;
}
// 百度小程序
else if (typeof swan !== undef) {
return swan;
}
// 抖音小程序 | 飞书小程序
else if (typeof tt !== undef) {
return tt;
}
// QQ 小程序
else if (typeof qq !== undef) {
return qq;
}
// 360 小程序
else if (typeof qh !== undef) {
return qh;
}
// 快手小程序
else if (typeof ks !== undef) {
return ks;
}
// 钉钉小程序
else if (typeof dd !== undef) {
return dd;
}
// 京东小程序
else if (typeof jd !== undef) {
return jd;
}
// 小红书小程序
else if (typeof xhs !== undef) {
return xhs;
}
}
function revisePlatformApiNames(platform?: AnyObject) {
if (platform) {
return {
request: platform.request ?? platform.httpRequest,
upload: platform.upload ?? platform.uploadFile,
download: platform.download ?? platform.downloadFile,
};
}
}
function isPlatform(value: any): value is AxiosAdapterPlatform {
return (
isPlainObject(value) &&
isFunction(value.request) &&
isFunction(value.upload) &&
isFunction(value.download)
);
}

View File

@ -1,23 +1,30 @@
import {
CancelToken,
CancelTokenConstructor,
isCancel,
} from './request/cancel';
import { isAxiosError } from './request/createError';
import Axios, { AxiosConstructor } from './core/Axios';
import { AxiosInstance, createInstance } from './core/createInstance';
import { createAdapter } from './adpater/createAdapter';
import { AxiosDomainRequest } from './core/AxiosDomain';
import Axios, {
AxiosConstructor,
AxiosRequestConfig,
AxiosRequestHeaders,
} from './core/Axios';
import { CancelToken, CancelTokenConstructor, isCancel } from './core/cancel';
import { isAxiosError } from './core/createError';
import { mergeConfig } from './core/mergeConfig';
import { createAdapter } from './adapter';
import defaults from './defaults';
import { version } from './version';
/**
* axios
*/
export interface AxiosStatic extends AxiosInstance {
export interface AxiosInstanceDefaults extends AxiosRequestConfig {
/**
*
*
*/
version: string;
headers: Required<AxiosRequestHeaders>;
}
export interface AxiosInstance extends AxiosDomainRequest, Axios {
/**
*
*/
defaults: AxiosInstanceDefaults;
}
export interface AxiosStatic extends AxiosInstance {
/**
* Axios
*/
@ -26,24 +33,48 @@ export interface AxiosStatic extends AxiosInstance {
*
*/
CancelToken: CancelTokenConstructor;
/**
* axios
*
* @param defaults
*/
create(defaults?: AxiosRequestConfig): AxiosInstance;
/**
*
*/
createAdapter: typeof createAdapter;
/**
* true
* Cancel
*/
isCancel: typeof isCancel;
/**
* true
* AxiosError
*/
isAxiosError: typeof isAxiosError;
}
function createInstance(defaults: AxiosRequestConfig) {
const context = new Axios(defaults);
const instance = context.request as AxiosInstance;
Object.assign(instance, context, {
// instance.fork 内部调用了 context 的私有方法
// 所以直接调用 instance.fork 会导致程序抛出无法访问 context 私有方法的异常
// instance.fork 调用时 this 重新指向 context解决此问题
fork: context.fork.bind(context),
});
Object.setPrototypeOf(instance, Object.getPrototypeOf(context));
return instance;
}
const axios = createInstance(defaults) as AxiosStatic;
axios.version = version;
axios.Axios = Axios;
axios.CancelToken = CancelToken;
axios.create = function create(defaults) {
return createInstance(mergeConfig(axios.defaults, defaults));
};
axios.createAdapter = createAdapter;
axios.isCancel = isCancel;
axios.isAxiosError = isAxiosError;

View File

@ -1,22 +0,0 @@
/**
*
*/
export const PLAIN_METHODS = ['options', 'trace', 'connect'] as const;
/**
*
*/
export const WITH_PARAMS_METHODS = ['head', 'get', 'delete'] as const;
/**
*
*/
export const WITH_DATA_METHODS = ['post', 'put', 'patch'] as const;
/**
* data
*/
export const WITH_DATA_RE = new RegExp(
`^(${WITH_DATA_METHODS.join('|')})`,
'i',
);

View File

@ -1,33 +1,23 @@
import {
PLAIN_METHODS,
WITH_DATA_METHODS,
WITH_PARAMS_METHODS,
} from '../constants/methods';
import { isString } from '../helpers/types';
import { dispatchRequest } from '../request/dispatchRequest';
import { CancelToken } from '../request/cancel';
import { AxiosTransformer } from '../request/transformData';
import { deepMerge } from '../helpers/deepMerge';
import { buildURL } from '../helpers/buildURL';
import { isAbsoluteURL } from '../helpers/isAbsoluteURL';
import { combineURL } from '../helpers/combineURL';
import { isString } from '../helpers/isTypes';
import {
AxiosAdapter,
AxiosAdapterRequestMethod,
AxiosAdapterPlatformTask,
AxiosAdapterTask,
AxiosAdapterResponse,
AxiosAdapterRequestConfig,
AxiosAdapterResponseError,
AxiosAdapterResponseData,
} from '../adpater/createAdapter';
import InterceptorManager, {
Interceptor,
InterceptorExecutor,
} from './InterceptorManager';
import MiddlewareManager, {
MiddlewareCallback,
MiddlewareContext,
} from './MiddlewareManager';
} from '../adapter';
import { mergeConfig } from './mergeConfig';
import { CancelToken } from './cancel';
import { dispatchRequest } from './dispatchRequest';
import { AxiosTransformer } from './transformData';
import AxiosDomain from './AxiosDomain';
import InterceptorManager from './InterceptorManager';
/**
*
*/
export type AxiosRequestMethod =
| AxiosAdapterRequestMethod
| 'options'
@ -40,9 +30,6 @@ export type AxiosRequestMethod =
| 'trace'
| 'connect';
/**
*
*/
export interface AxiosRequestHeaders extends AnyObject {
/**
*
@ -82,9 +69,6 @@ export interface AxiosRequestHeaders extends AnyObject {
connect?: AnyObject;
}
/**
*
*/
export interface AxiosRequestFormData extends AnyObject {
/**
*
@ -96,75 +80,29 @@ export interface AxiosRequestFormData extends AnyObject {
filePath: string;
}
/**
*
*/
export type AxiosRequestData =
| string
| AnyObject
| ArrayBuffer
| AxiosRequestFormData;
export type AxiosRequestData = AnyObject | AxiosRequestFormData;
/**
*
*/
export type AxiosResponseData = number | AxiosAdapterResponseData;
export type AxiosResponseData = undefined | number | AxiosAdapterResponseData;
/**
*
*/
export interface AxiosProgressEvent extends AnyObject {
export interface AxiosProgressEvent {
/**
*
*
*/
progress: number;
}
/**
*
*/
export interface AxiosDownloadProgressEvent extends AxiosProgressEvent {
/**
* Bytes
*/
totalBytesWritten: number;
/**
* Bytes
*/
totalBytesExpectedToWrite: number;
}
/**
*
*/
export interface AxiosDownloadProgressCallback {
(event: AxiosDownloadProgressEvent): void;
}
/**
*
*/
export interface AxiosUploadProgressEvent extends AxiosProgressEvent {
/**
* Bytes
*
*/
totalBytesSent: number;
/**
* Bytes
*
*/
totalBytesExpectedToSend: number;
}
/**
*
*/
export interface AxiosUploadProgressCallback {
(event: AxiosUploadProgressEvent): void;
export interface AxiosProgressCallback {
(event: AxiosProgressEvent): void;
}
/**
*
*/
export interface AxiosRequestConfig
extends Partial<
Omit<AxiosAdapterRequestConfig, 'type' | 'success' | 'fail'>
@ -202,21 +140,13 @@ export interface AxiosRequestConfig
*/
cancelToken?: CancelToken;
/**
*
*/
download?: boolean;
/**
*
*
*/
upload?: boolean;
/**
*
*
*/
paramsSerializer?: (params?: AnyObject) => string;
/**
*
*/
validateStatus?: (status: number) => boolean;
download?: boolean;
/**
*
*/
@ -228,69 +158,43 @@ export interface AxiosRequestConfig
/**
*
*/
errorHandler?: (error: unknown) => Promise<AxiosResponse>;
/**
*
*/
onDownloadProgress?: AxiosUploadProgressCallback;
errorHandler?: (error: unknown) => Promise<void> | void;
/**
*
*/
onUploadProgress?: AxiosUploadProgressCallback;
onUploadProgress?: AxiosProgressCallback;
/**
*
*/
onDownloadProgress?: AxiosProgressCallback;
/**
*
*/
paramsSerializer?: (params?: AnyObject) => string;
/**
*
*/
validateStatus?: (status: number) => boolean;
}
/**
*
*/
export interface AxiosResponse<
TData extends AxiosResponseData = AxiosResponseData,
> extends AnyObject {
> extends Omit<AxiosAdapterResponse, 'data'> {
/**
*
*
*/
status: number;
config?: AxiosRequestConfig;
/**
*
*
*/
statusText: string;
/**
*
*/
headers: AnyObject;
request?: AxiosAdapterTask;
/**
*
*/
data: TData;
/**
*
*/
config: AxiosRequestConfig;
/**
*
*/
request?: AxiosAdapterPlatformTask;
}
/**
*
*/
export interface AxiosResponseError extends AnyObject {
/**
*
*/
status: number;
/**
*
*/
statusText: string;
/**
*
*/
headers: AnyObject;
/**
*
*/
data: AnyObject;
export interface AxiosResponseError extends AxiosAdapterResponseError {
/**
*
*/
@ -298,73 +202,18 @@ export interface AxiosResponseError extends AnyObject {
/**
*
*/
config: AxiosRequestConfig;
config?: AxiosRequestConfig;
/**
*
*/
request?: AxiosAdapterPlatformTask;
request?: AxiosAdapterTask;
}
export interface AxiosRequest {
<TData extends AxiosResponseData>(config: AxiosRequestConfig): Promise<
AxiosResponse<TData>
>;
<TData extends AxiosResponseData>(
url: string,
config?: AxiosRequestConfig,
): Promise<AxiosResponse<TData>>;
}
/**
*
*/
export type AxiosRequestMethodFn = <TData extends AxiosResponseData>(
url: string,
config?: AxiosRequestConfig,
) => Promise<AxiosResponse<TData>>;
/**
*
*/
export type AxiosRequestMethodFnWithParams = <TData extends AxiosResponseData>(
url: string,
params?: AnyObject,
config?: AxiosRequestConfig,
) => Promise<AxiosResponse<TData>>;
/**
*
*/
export type AxiosRequestMethodFnWithData = <TData extends AxiosResponseData>(
url: string,
data?: AxiosRequestData,
config?: AxiosRequestConfig,
) => Promise<AxiosResponse<TData>>;
export interface AxiosDomainRequestHandler {
(config: AxiosRequestConfig): Promise<AxiosResponse>;
}
/**
* Axios
*/
export interface AxiosConstructor {
new (config: AxiosRequestConfig): Axios;
}
export default class Axios {
/**
* @internal
*
*
*/
private declare parent?: Axios;
/**
*
*/
declare defaults: AxiosRequestConfig;
export default class Axios extends AxiosDomain {
/**
*
*/
@ -379,219 +228,41 @@ export default class Axios {
response: new InterceptorManager<AxiosResponse>(),
};
/**
* @internal
*
*
*/
private middleware = new MiddlewareManager();
constructor(defaults: AxiosRequestConfig = {}) {
super(defaults, (config) => this.#processRequest(config));
}
/**
* options
*/
declare options: AxiosRequestMethodFn;
/**
* get
*/
declare get: AxiosRequestMethodFnWithParams;
/**
* head
*/
declare head: AxiosRequestMethodFnWithParams;
/**
* post
*/
declare post: AxiosRequestMethodFnWithData;
/**
* put
*/
declare put: AxiosRequestMethodFnWithData;
/**
* patch
*/
declare patch: AxiosRequestMethodFnWithData;
/**
* delete
*/
declare delete: AxiosRequestMethodFnWithParams;
/**
* trace
*/
declare trace: AxiosRequestMethodFn;
/**
* connect
*/
declare connect: AxiosRequestMethodFn;
/**
* @param config
* @param parent
*/
constructor(config: AxiosRequestConfig, parent?: Axios) {
this.defaults = config;
this.parent = parent;
getUri(config: AxiosRequestConfig): string {
const { url, params, paramsSerializer } = mergeConfig(
this.defaults,
config,
);
return buildURL(url, params, paramsSerializer).replace(/^\?/, '');
}
/**
*
*
*/
request: AxiosRequest = (
urlOrConfig: string | AxiosRequestConfig,
config: AxiosRequestConfig = {},
) => {
if (isString(urlOrConfig)) {
config.url = urlOrConfig;
} else {
config = urlOrConfig;
fork(defaults: AxiosRequestConfig = {}) {
if (isString(defaults.baseURL) && !isAbsoluteURL(defaults.baseURL)) {
defaults.baseURL = combineURL(this.defaults.baseURL, defaults.baseURL);
}
config = mergeConfig(this.defaults, config);
config.method = (config.method?.toLowerCase() ??
'get') as AxiosRequestMethod;
return new AxiosDomain(mergeConfig(this.defaults, defaults), (config) =>
this.#processRequest(config),
);
}
const requestHandler = {
resolved: this.handleRequest,
};
const errorHandler = {
rejected: config.errorHandler,
};
const chain: (
| Partial<Interceptor<AxiosRequestConfig>>
| Partial<Interceptor<AxiosResponse>>
)[] = [];
#processRequest(config: AxiosRequestConfig) {
const { request, response } = this.interceptors;
this.eachInterceptors('request', (interceptor) => {
chain.unshift(interceptor);
let promiseRequest = Promise.resolve(config);
request.forEach(({ resolved, rejected }) => {
promiseRequest = promiseRequest.then(resolved, rejected);
}, true);
let promiseResponse = promiseRequest.then(dispatchRequest);
response.forEach(({ resolved, rejected }) => {
promiseResponse = promiseResponse.then(resolved, rejected);
});
chain.push(requestHandler);
this.eachInterceptors('response', (interceptor) => {
chain.push(interceptor);
});
chain.push(errorHandler);
return chain.reduce(
(next, { resolved, rejected }) =>
next.then(
// @ts-ignore
resolved,
rejected,
),
Promise.resolve(config),
) as Promise<AxiosResponse>;
};
/**
* @internal
*/
private eachInterceptors<T extends 'request' | 'response'>(
type: T,
executor: InterceptorExecutor<
T extends 'request' ? AxiosRequestConfig : AxiosResponse
>,
) {
// @ts-ignore
this.interceptors[type].forEach(executor);
if (this.parent) {
this.parent.eachInterceptors(type, executor);
}
return promiseResponse;
}
/**
*
*
* 1
* ```ts
* axios.use(async function middleware(ctx, next) {
* console.log(ctx.req);
* await next();
* console.log(ctx.res);
* });
* ```
*
* 2
* ```ts
* axios
* .use(async function middleware1(ctx, next) {
* console.log(ctx.req);
* await next();
* console.log(ctx.res);
* })
* .use(async function middleware2(ctx, next) {
* console.log(ctx.req);
* await next();
* console.log(ctx.res);
* });
* ```
*/
use = (middleware: MiddlewareCallback) => {
this.middleware.use(middleware);
return this;
};
/**
* @internal
*/
private handleRequest = async (config: AxiosRequestConfig) => {
const ctx = this.middleware.createContext(config);
await this.run(ctx, this.handleResponse);
return ctx.res as AxiosResponse;
};
/**
* @internal
*/
private async handleResponse(ctx: MiddlewareContext) {
ctx.res = await dispatchRequest(ctx.req);
}
/**
* @internal
*/
private 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);
};
}
for (const method of PLAIN_METHODS) {
Axios.prototype[method] = function processRequestMethod(url, config = {}) {
config.method = method;
return this.request(url, config);
};
}
for (const method of WITH_PARAMS_METHODS) {
Axios.prototype[method] = function processRequestMethodWithParams(
url,
params,
config = {},
) {
config.method = method;
config.params = deepMerge(params, config.params);
return this.request(url, config);
};
}
for (const method of WITH_DATA_METHODS) {
Axios.prototype[method] = function processRequestMethodWithData(
url,
data,
config = {},
) {
config.method = method;
config.data = data;
return this.request(url, config);
};
}

204
src/core/AxiosDomain.ts Normal file
View File

@ -0,0 +1,204 @@
import { isString, isUndefined } from '../helpers/isTypes';
import { deepMerge } from '../helpers/deepMerge';
import { mergeConfig } from './mergeConfig';
import {
AxiosRequestConfig,
AxiosRequestData,
AxiosResponse,
AxiosResponseData,
} from './Axios';
export interface AxiosDomainRequest {
<TData extends AxiosResponseData>(
/**
*
*/
config: AxiosRequestConfig,
): Promise<AxiosResponse<TData>>;
<TData extends AxiosResponseData>(
/**
*
*/
url: string,
/**
*
*/
config?: AxiosRequestConfig,
): Promise<AxiosResponse<TData>>;
}
export interface AxiosDomainAsRequest {
<TData extends AxiosResponseData>(
/**
*
*/
url: string,
/**
*
*/
config?: AxiosRequestConfig,
): Promise<AxiosResponse<TData>>;
}
export interface AxiosDomainAsRequestWithParams {
<TData extends AxiosResponseData>(
/**
*
*/
url: string,
/**
*
*/
params?: AnyObject,
/**
*
*/
config?: AxiosRequestConfig,
): Promise<AxiosResponse<TData>>;
}
export interface AxiosDomainAsRequestWithData {
<TData extends AxiosResponseData>(
/**
*
*/
url: string,
/**
*
*/
data?: AxiosRequestData,
/**
*
*/
config?: AxiosRequestConfig,
): Promise<AxiosResponse<TData>>;
}
export default class AxiosDomain {
/**
*
*/
static as = ['options', 'trace', 'connect'] as const;
/**
*
*/
static asp = ['head', 'get', 'delete'] as const;
/**
*
*/
static asd = ['post', 'put', 'patch'] as const;
/**
*
*/
defaults: AxiosRequestConfig;
/**
*
*/
request!: AxiosDomainRequest;
/**
* options
*/
options!: AxiosDomainAsRequest;
/**
* get
*/
get!: AxiosDomainAsRequestWithParams;
/**
* head
*/
head!: AxiosDomainAsRequestWithParams;
/**
* post
*/
post!: AxiosDomainAsRequestWithData;
/**
* put
*/
put!: AxiosDomainAsRequestWithData;
/**
* patch
*/
patch!: AxiosDomainAsRequestWithData;
/**
* delete
*/
delete!: AxiosDomainAsRequestWithParams;
/**
* trace
*/
trace!: AxiosDomainAsRequest;
/**
* connect
*/
connect!: AxiosDomainAsRequest;
constructor(
defaults: AxiosRequestConfig,
processRequest: (config: AxiosRequestConfig) => Promise<AxiosResponse>,
) {
this.defaults = defaults;
this.request = (
urlOrConfig: string | AxiosRequestConfig,
config: AxiosRequestConfig = {},
) => {
if (isString(urlOrConfig)) {
config.url = urlOrConfig;
} else {
config = urlOrConfig;
}
if (isUndefined(config.method)) {
config.method = 'get';
}
return processRequest(mergeConfig(this.defaults, config));
};
this.#createAsRequests();
this.#createAspRequests();
this.#createAsdRequests();
}
#createAsRequests() {
for (const alias of AxiosDomain.as) {
this[alias] = function processAsRequest(url, config = {}) {
config.method = alias;
return this.request(url, config);
};
}
}
#createAspRequests() {
for (const alias of AxiosDomain.asp) {
this[alias] = function processAspRequest(url, params = {}, config = {}) {
config.method = alias;
config.params = deepMerge(params, config.params ?? {});
return this.request(url, config);
};
}
}
#createAsdRequests() {
for (const alias of AxiosDomain.asd) {
this[alias] = function processAsdRequest(url, data = {}, config = {}) {
config.method = alias;
config.data = deepMerge(data, config.data ?? {});
return this.request(url, config);
};
}
}
}

View File

@ -6,17 +6,8 @@ export interface InterceptorRejected<T = unknown> {
(error: unknown): T | Promise<T>;
}
/**
*
*/
export interface Interceptor<T = unknown> {
/**
*
*/
resolved: InterceptorResolved<T>;
/**
*
*/
rejected?: InterceptorRejected<T>;
}
@ -24,76 +15,30 @@ export interface InterceptorExecutor<T = unknown> {
(interceptor: Interceptor<T>): void;
}
/**
*
*/
export default class InterceptorManager<T = unknown> {
/**
* @internal
*
*
*/
private id = 0;
#id = 0;
/**
* @internal
*
*
*/
private interceptors = new Map<number, Interceptor<T>>();
#interceptors: AnyObject<Interceptor<T>> = {};
/**
* @internal
*
*
*/
get size() {
return this.interceptors.size;
}
/**
*
*
* @param resolved
* @param rejected
* @returns
*/
use(
resolved: InterceptorResolved<T>,
rejected?: InterceptorRejected<T>,
): number {
this.interceptors.set(++this.id, {
this.#interceptors[++this.#id] = {
resolved,
rejected,
});
};
return this.id;
return this.#id;
}
/**
*
*
* @param id
*/
eject(id: number): boolean {
return this.interceptors.delete(id);
eject(id: number): void {
delete this.#interceptors[id];
}
/**
*
*/
clear() {
this.interceptors.clear();
}
/**
* @internal
*
*
*
* @param executor
*/
forEach(executor: InterceptorExecutor<T>): void {
this.interceptors.forEach(executor);
forEach(executor: InterceptorExecutor<T>, reverse?: boolean): void {
let interceptors: Interceptor<T>[] = Object.values(this.#interceptors);
if (reverse) interceptors = interceptors.reverse();
interceptors.forEach(executor);
}
}

Some files were not shown because too many files have changed in this diff Show More