Skip to content

@wenext/network v1.0.0

WeNext 统一网络请求库,支持客户端桥接优先、axios 降级。

特性

  • ⚡ 零配置开箱即用
  • 🚀 App 内自动使用客户端桥接,浏览器自动降级 axios
  • 🔄 桥接超时自动降级(30s)
  • 🎯 一套代码同时支持 App 和浏览器
  • 📦 支持 Vue 2/3
  • 💪 完整 TypeScript 支持

安装

bash
pnpm add @wenext/network

使用指南

1. 零配置使用(推荐)

适用于大部分场景,无需任何配置即可使用。

typescript
import * as http from '@wenext/network'

// 发起请求
const response = await http.get('/api/user/info')
const result = await http.post('/api/user/update', { name: 'John' })

// 响应结构
console.log(response.code)     // 200
console.log(response.data)     // 业务数据
console.log(response.message)  // 消息

自动完成的事情

  • 读取 process.env.VUE_APP_SERVICE_URL 作为 baseURL
  • App 内自动注入客户端 headers(token、language_code、version_code 等)
  • 自动检测环境并选择最优请求方式(桥接 or axios)
  • 桥接超时(30s)自动降级到 axios(仅 GET 请求)

2. 自定义网络实例

需要自定义配置时使用。

typescript
import { createNetwork } from '@wenext/network'

const network = createNetwork({
  baseURL: 'https://api.example.com',
  timeout: 30000,
  requestInterceptors: [
    async (config) => {
      // 自定义请求头
      return { ...config, headers: { ...config.headers, 'X-Custom': 'value' } }
    }
  ],
  responseInterceptors: [
    async (response) => {
      // 统一错误处理
      if (response.code === 501) router.push('/login')
      return response
    }
  ]
})

await network.get('/users')

3. 动态配置(高级)

适用于需要动态获取 token、baseURL 等场景。

typescript
import { createUnifiedClient } from '@wenext/network'

const client = createUnifiedClient(async () => {
  // 每次请求前动态获取配置
  const token = await getTokenFromStore()
  return {
    baseURL: import.meta.env.VUE_APP_SERVICE_URL,
    headers: { 'Authorization': `Bearer ${token}` },
    useBridge: false  // 可选:强制使用 axios
  }
})

await client.get('/api/data')

4. API Generator 接入

适用于已有 axios 实例的项目,可以无缝接入。

typescript
import axios from 'axios'
import { createNetwork } from '@wenext/network'

// 1. 保留现有 axios 实例和配置
const axiosInstance = axios.create({
  baseURL: import.meta.env.VUE_APP_API_URL,
  timeout: 30000,
  withCredentials: true
})

// 2. 保留现有拦截器
axiosInstance.interceptors.request.use(...)
axiosInstance.interceptors.response.use(...)

// 3. 注入到 @wenext/network
const network = createNetwork({
  axiosInstance  // 注入现有实例,获得桥接能力
})

// 4. 使用 network 替代 axios
await network.get('/api/user')

5. Vue 集成

Vue 3 Composables

vue
<script setup>
import { useRequest, usePagination } from '@wenext/network/composables'

// 单次请求
const { data, loading, execute } = useRequest({
  url: '/api/user/info',
  immediate: true
})

// 分页列表
const { list, loading, hasMore, loadMore, refresh } = usePagination({
  url: '/api/users',
  pageSize: 20
})
</script>

<template>
  <div v-if="loading">加载中...</div>
  <div v-else>{{ data }}</div>
</template>

Vue 2 Mixin

javascript
import { requestMixin } from '@wenext/network/vue2'

export default {
  mixins: [requestMixin],
  methods: {
    async fetchData() {
      const res = await this.$get('/api/user/info')
      if (res.code === 200) {
        this.userData = res.data
      }
    }
  }
}

常用 API

请求方法

typescript
import { get, post, put, del, patch } from '@wenext/network'

// GET 请求
await get('/api/users')
await get('/api/users', { params: { page: 1 } })

// POST 请求
await post('/api/users', { name: 'John' })

// PUT 请求
await put('/api/users/1', { name: 'Jane' })

// DELETE 请求
await del('/api/users/1')

// PATCH 请求
await patch('/api/users/1', { status: 'active' })

响应码常量

typescript
import { RES_COMMON_CODE } from '@wenext/network'

if (response.code === RES_COMMON_CODE.SUCCESS) {
  // 成功
}

if (response.code === RES_COMMON_CODE.TOKEN_EXPIRE) {
  // token 过期,跳转登录
}

// 常用响应码
RES_COMMON_CODE.SUCCESS           // 200
RES_COMMON_CODE.TOKEN_EXPIRE      // 501
RES_COMMON_CODE.NO_PERMISSION     // 502

环境检测

typescript
import { isBridgeAvailable, isInApp } from '@wenext/network'

const inApp = isInApp()                    // 是否在 App 内
const hasBridge = isBridgeAvailable()      // 桥接是否可用

配置选项

typescript
// 跳过 region header 注入
await get('/api/data', { skipRegion: true })

// 自定义超时时间
await get('/api/data', { timeout: 60000 })

// 桥接降级超时(0 表示不降级)
await get('/api/data', { bridgeFallbackTimeout: 0 })

// 获取当前请求方式
const type = await network.getCurrentRequestType() // 'bridge' 或 'axios'

降级策略

  • GET 请求:桥接超时(30s)后自动降级到 axios
  • POST/PUT/DELETE/PATCH:桥接超时后返回错误(避免重复提交)

响应结构

typescript
interface NetworkResponse<T> {
  code: number      // 业务状态码
  data: T | null    // 业务数据
  message: string   // 消息
  raw?: unknown     // 原始响应(调试用)
}

迁移指南

从 @mono/network-v3 迁移

typescript
// 原代码
import * as http from "@mono/network-v3/unified"
const result = await http.get('/api/user')

// 新代码(零改动)
import * as http from '@wenext/network'
const result = await http.get('/api/user')

从 @mono/network 迁移

typescript
// 原代码
import http from "@mono/network"
const result = await http.get('/api/user')

// 新代码
import { defaultNetwork } from '@wenext/network'
const result = await defaultNetwork.get('/api/user')

// 或使用快捷方法
import { get } from '@wenext/network'
const result = await get('/api/user')