@wlydfe/service
v1.1.2
Published
npm service
Keywords
Readme
@wlydfe/service
一个基于 Axios 的 HTTP 服务封装库,提供了完整的 TypeScript 支持和丰富的配置选项。
特性
- 🚀 基于 Axios - 强大的 HTTP 请求库
- 📦 TypeScript - 完整的类型定义支持
- 🔧 灵活配置 - 丰富的配置选项和自定义能力
- 🚫 请求取消 - 自动取消重复请求
- 🔄 数据转换 - 支持请求和响应数据的自定义转换
- 🎯 错误处理 - 统一的错误处理机制
- 🌐 网关支持 - 支持多种网关和URL前缀配置
- 📋 表单数据 - 支持 form-data 和 form-urlencoded 格式
- 📖 拦截器 - 支持请求和响应拦截器
- 🎨 消息提示 - 支持多种消息提示模式
安装
pnpm add @wlydfe/service基本使用
创建服务实例
import { ContentTypeEnum, RequestEnum, VAxios } from '@wlydfe/service'
// 创建服务实例
const http = new VAxios({
baseURL: 'https://api.example.com',
timeout: 10000,
headers: {
'Content-Type': ContentTypeEnum.JSON,
},
})
// 发送 GET 请求
const response = await http.get({
url: '/users',
})
// 发送 POST 请求
const response = await http.post({
url: '/users',
data: { name: 'John', age: 30 },
})使用配置选项
import type { CreateAxiosOptions } from '@wlydfe/service'
const options: CreateAxiosOptions = {
baseURL: 'https://api.example.com',
timeout: 30000,
requestOptions: {
// 是否拼接URL前缀
joinPrefix: true,
// 是否处理响应数据
isTransformResponse: true,
// 错误消息提示类型
errorMessageMode: 'message',
// 是否携带token
withToken: true,
},
}
const http = new VAxios(options)高级功能
自定义拦截器
import type { AxiosTransform } from '@wlydfe/service'
const transform: AxiosTransform = {
// 请求前处理
beforeRequestHook: (config, options) => {
// 添加API前缀
if (options.joinPrefix) {
config.url = `/api${config.url}`
}
return config
},
// 请求拦截器
requestInterceptors: (config) => {
// 添加认证token
const token = getToken()
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
},
// 响应拦截器
responseInterceptors: (response) => {
return response
},
// 响应数据转换
transformResponseHook: (response, options) => {
const { data } = response
if (data.succeed) {
return data
}
throw new Error(data.message || '请求失败')
},
}
const http = new VAxios({
baseURL: 'https://api.example.com',
transform,
})网关和URL前缀
import { GatewayEnum, UrlPrefixEnum } from '@wlydfe/service'
const http = new VAxios({
baseURL: 'https://api.example.com',
requestOptions: {
joinPrefix: true,
urlGateway: GatewayEnum.GATEWAY,
urlPrefix: UrlPrefixEnum.PLATFORM,
},
})
// 实际请求URL: https://api.example.com/gateway/platform/users
const response = await http.get({ url: '/users' })取消请求
// 创建取消信号
const controller = new AbortController()
// 发送可取消的请求
const response = await http.get({
url: '/users',
signal: controller.signal,
})
// 取消请求
controller.abort()配置选项
RequestOptions
interface RequestOptions {
/** 是否将请求参数拼接至url */
joinParamsToUrl?: boolean
/** 是否处理请求结果 */
isTransformResponse?: boolean
/** 是否返回原生响应头 */
isReturnNativeResponse?: boolean
/** 是否拼接url前缀 */
joinPrefix?: boolean
/** 接口地址 */
baseURL?: string
/** 网关 */
urlGateway?: string
/** url前缀 */
urlPrefix?: UrlPrefixEnum
/** 错误消息提示类型 */
errorMessageMode?: MessageModeEnum
/** 成功消息提示类型 */
successMessageMode?: MessageModeEnum
/** 是否添加时间戳 */
joinTime?: boolean
/** 是否忽略重复请求 */
ignoreCancelToken?: boolean
/** 是否在header中发送token */
withToken?: boolean
}响应数据格式
interface BaseRes<T = any> {
/** 是否成功 */
succeed: boolean
/** 错误码 */
code: string
/** 错误信息 */
message: string
/** 数据 */
model: T
/** 总数 */
total?: number
/** 异常编码 */
errCode?: string
/** 异常信息 */
errMsg?: string
}枚举类型
请求方法
enum RequestEnum {
GET = 'GET',
POST = 'POST',
PUT = 'PUT',
DELETE = 'DELETE',
}内容类型
enum ContentTypeEnum {
JSON = 'application/json;charset=UTF-8',
FORM_URLENCODED = 'application/x-www-form-urlencoded;charset=UTF-8',
FORM_DATA = 'multipart/form-data;charset=UTF-8',
}示例项目
项目中包含了一个完整的示例项目,位于 example/ 目录下,展示了如何在实际项目中使用这个库。
cd example
npm install
npm run dev开发
# 安装依赖
pnpm install
# 开发模式
pnpm run dev
# 构建
pnpm run build
# 类型检查
pnpm run typecheck
# 代码检查
pnpm run lint
# 运行测试
pnpm run test错误处理
配置错误处理回调
import { configureErrorHandler } from '@wlydfe/service'
configureErrorHandler({
// Token失效回调
onTokenExpired: () => {
console.log('Token expired, redirecting to login...')
localStorage.removeItem('token')
window.location.href = '/login'
},
// 弹窗回调
onShowModal: (message: string, status?: number) => {
console.log(`Modal: ${message} (Status: ${status})`)
// 集成你的UI库弹窗组件
// ElMessageBox.alert(message, '错误提示')
},
// Toast回调
onShowToast: (message: string, status?: number) => {
console.log(`Toast: ${message} (Status: ${status})`)
// 集成你的UI库toast组件
// ElMessage.error(message)
},
})手动触发错误处理
import { checkStatus } from '@wlydfe/service'
// 检查HTTP状态码并处理错误
checkStatus(401, '用户认证失败', 'message') // 会触发token失效回调和toast回调
checkStatus(500, '服务器内部错误', 'modal') // 会触发弹窗回调完整枚举类型
URL前缀枚举
enum UrlPrefixEnum {
/** 大宗小程序/app */
CTP_APP = '/ctp-app',
/** 大宗门户 */
CTP_PORTAL = '/ctp-portal',
/** 大宗用户端 */
CTP_USER = '/ctp-user',
/** 大宗平台端 */
CTP_PLATFORM = '/ctp-platform',
/** 平台 */
PLATFORM = '/platform',
/** AI大模型 */
AIM_PLATFORM = '/aim-platform',
}网关枚举
enum GatewayEnum {
GATEWAY = '/gateway',
}结果枚举
enum ResultEnum {
SUCCESS = 0,
ERROR = -1,
TIMEOUT = 401,
TYPE = 'success',
}文档链接
特性亮点
- ✨ 类型安全: 完整的 TypeScript 类型定义
- 🔄 自动重试: 支持请求失败自动重试
- 🚫 请求去重: 自动取消重复请求
- 🔐 Token管理: 内置token失效处理和自动刷新
- 📱 多环境: 支持开发、测试、生产环境配置
- 🎯 错误统一: 统一的错误处理和提示机制
- 🌐 多网关: 支持多种网关和URL前缀
- 📋 多格式: 支持JSON、表单、文件上传等多种数据格式
更新日志
v1.0.6 (最新)
- 🔧 修复了错误处理配置的问题
- 📝 优化了类型定义
- ✨ 增加了更多的配置选项
- 📚 完善了文档和示例
v1.0.5
- ✨ 添加了错误处理模块
- 🔧 支持自定义错误回调
- 📝 优化了文档结构
贡献指南
我们欢迎所有形式的贡献,包括但不限于:
- 🐛 报告bug
- 💡 提出新功能建议
- 📝 改进文档
- 🔧 修复问题
- ✨ 添加新功能
开发流程
- Fork 本仓库
- 创建特性分支:
git checkout -b feature/amazing-feature - 提交更改:
git commit -m 'Add amazing feature' - 推送到分支:
git push origin feature/amazing-feature - 创建 Pull Request
支持
如果您在使用过程中遇到问题,可以通过以下方式获得帮助:
- 📋 提交 Issue
- 📧 发送邮件至: [email protected]
- 💬 查看 FAQ
许可证
MIT License © 2021-PRESENT goodswifter
