npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@db-rn/request

v1.0.0

Published

React Native 通用请求核心库,提供 HTTP(fetch/axios 双引擎)与 SSE 能力,供主应用与子应用共用

Readme

db-rn-request

React Native 通用请求核心库,提供 HTTP(fetch / axios 双引擎)SSE(流式推送) 能力,供主应用与子应用共用。

设计上参考了 node-fetch 的极简思路,但优先 React Native 环境:默认使用 fetch 引擎,axios 为可选引擎。

特性

  • 🚀 默认 fetch 引擎,RN 原生友好;axios 作为可选引擎(按需安装)
  • 🔌 依赖注入:取 Token、401 处理、错误提示均由使用者传入,核心库零业务耦合
  • 🧩 请求 / 响应 / 错误 三类拦截器
  • ⏱️ 超时控制与失败重试
  • 📦 统一响应结构 ApiResponse<T> 与统一错误 HttpError
  • 📡 SSE 客户端,兼容 RN 的响应体读取限制,支持打字机式输出
  • 🧾 统一日志开关,生产环境默认静默

安装

npm install db-rn-request
# 如需使用 axios 引擎,再安装 axios(可选)
npm install axios

react-native 为 peer 依赖;axios 为可选 peer 依赖。

设计说明:为什么用「使用者传入」而非「项目配置」

核心库要被主应用和子应用共用,因此不能耦合任何具体项目的实现(如某个 UserStorageclearUserDataDbToast)。 本库将以下能力全部改为依赖注入(使用者传入)

| 能力 | 注入方式 | 说明 | | --- | --- | --- | | 获取 Token | getToken | 由使用者从自己的存储中读取 | | 鉴权头格式 | authHeaderName / authScheme | 默认 Authorization + Bearer | | 401 未授权处理 | onUnauthorized | 由使用者清理登录态、跳转登录页 | | 错误提示 | onError | 由使用者决定是否 Toast,核心库不依赖任何 UI 库 | | 错误上报 | setErrorReporter | 由使用者对接监控平台 |

这样既保证核心库纯净可移植,又能让每个应用按需接入自己的 storage / auth / UI。

快速开始(HTTP)

在应用入口处初始化一次(注入业务能力):

import { http } from 'db-rn-request';
import { UserStorage } from '@/utils/storage-service';
import { clearUserData } from '@/api/auth';
import { DbToast } from 'db-rn-ui';

http.init({
  baseUrl: 'https://api.example.com',
  timeout: 30000,
  engine: 'fetch', // 默认即 fetch,可选 'axios'

  // 注入取 Token 逻辑
  getToken: () => UserStorage.getToken(),

  // 注入 401 处理逻辑
  onUnauthorized: async () => {
    await UserStorage.removeToken();
    await clearUserData();
    // 跳转登录页...
  },

  // 注入错误提示逻辑(核心库不直接依赖 db-rn-ui)
  onError: (error) => {
    if (error.status === 404) DbToast.info('资源不存在');
  },
});

发起请求:

import { http, get, post } from 'db-rn-request';

// 使用单例
const res = await http.get<UserInfo>('/user/info');
if (res.success) {
  console.log(res.data);
}

// 或使用便捷方法
await post('/order/create', { skuId: 1 });

拦截器

import { http } from 'db-rn-request';

// 请求拦截器
const removeReq = http.addRequestInterceptor((config) => {
  config.headers = { ...config.headers, 'X-Trace-Id': genTraceId() };
  return config;
});

// 响应拦截器
http.addResponseInterceptor((data) => data);

// 错误拦截器(返回非 undefined 即作为兜底结果)
http.addErrorInterceptor((err) => {
  if (err.status === 0) return { code: -1, data: null, message: '网络异常', success: false };
});

文件上传

await http.upload('/upload', [
  { uri: 'file:///path/photo.jpg', type: 'image/jpeg', name: 'photo.jpg' },
], 'file', { bizType: 'avatar' });

快速开始(SSE)

import { sseClient } from 'db-rn-request';

const cancel = await sseClient.connect('https://api.example.com/ai/chat', {
  method: 'POST',
  headers: { Authorization: `Bearer ${token}` },
  body: { prompt: '你好' },
  onOpen: () => console.log('连接已建立'),
  onMessage: (msg) => appendText(msg.data),
  onComplete: () => console.log('输出完成'),
  onError: (e) => console.warn(e.message),
});

// 需要时主动断开
cancel();

构建与发布

npm run build   # 通过 rollup 输出 lib/(cjs + esm + d.ts)
npm run release # 构建并发布到 npm

目录结构

src/
  core/
    types.ts        # 核心类型定义
    errors.ts       # HttpError
    logger.ts       # 统一日志工具
    http-client.ts  # HTTP 核心客户端(fetch / axios)
    sse-client.ts   # SSE 客户端
  index.ts          # 唯一对外出口