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

@cclr/service

v0.1.61

Published

接口请求服务

Readme

service

轻量 HTTP 客户端与业务 Service 基类(基于 fetch + 拦截器,axios 风格 API)。

Usage

npm i @cclr/service
import {
  BizBaseService,
  createServiceHandle,
  createAxiosBizError,
  type AxiosResponse,
} from '@cclr/service';

// 继承 BizBaseService,按需覆写扩展点
class UserService extends BizBaseService {
  constructor() {
    super({ baseURL: 'https://api.example.com' });
  }

  protected resolveHeadersOnRequest(headers) {
    return { ...headers, Authorization: 'Bearer token' };
  }

  protected resolveResponse(response: AxiosResponse) {
    const { ret, val, msg } = response.data ?? {};
    if (ret !== 0) {
      return Promise.reject(createAxiosBizError(response, { message: msg }));
    }
    response.data = val;
  }

  getUser(id: string) {
    return this.get<{ name: string }>('/user', { id });
  }
}

const userService = new UserService();
const user = await userService.getUser('1');

// 包装 toast / 错误格式化
const api = createServiceHandle(userService, {
  showToastError: (err) => console.error(err.message),
});
await api.get('/user', { id: '1' });

API 说明

核心类

  • Axios:轻量 HTTP 客户端,合并配置、跑拦截器、调用 adapterrequest 返回响应拦截器处理后的 response.data
  • BaseService:通用 Service 基类,封装 get/post/put/patch/delete/head/options,提供三个扩展点:
    • resolveHeadersOnRequest(headers, config):请求发出前合并/注入请求头。
    • resolveResponse(response):成功响应处理,可校验业务码、改写 response.data
    • resolveErrorResponse(error):失败响应处理,建议只做副作用(提示/日志),不要 throw。

场景基类

  • BizBaseService:业务 JSON API 基类,默认 responseType: 'json'Content-Type: application/jsonFormData 请求时自动移除 Content-Type
  • ServiceBase:旧版基类,响应拦截器自动尝试 JSON 解析字符串 body;提供 postFormdata 与单例 create()
  • ServiceFile:文件场景基类,单例 create()

请求包装

  • serviceWrapper(fetchFn, options?):包装单次请求,支持响应格式化、错误格式化、toast 控制。
  • createServiceHandle(service, options):基于 BaseService 创建带包装的 get/post 调用器。
  • IServiceWrapperOptions:包装选项类型(hideToast/formatResponseData/formatErrorResponse/showToastError)。

适配器

  • adaptRequestFetch:默认 fetch 适配器,拼 URL、发请求、按 responseType 解析 body;HTTP 非 2xx 或网络失败时 reject AxiosError
  • createRequestAdapterUni(request):创建 uni.request 适配器,用于小程序等环境。
  • toAxiosHeaders(res):将 uni 响应头转为普通对象。
  • resolveUniResponseOptions(responseType?):映射 responseType → uni.request 参数。

工具函数

  • mergeAxiosRequestConfig(defaultConfig, config):合并请求配置,顶层字段后者覆盖,headers 浅合并。
  • resolveRequestUrl(url, baseURL?):合并请求地址,无域名时拼接 baseURL
  • resolveBody(data?):将请求体转为 fetch 可接受的 BodyInit
  • resolveConfigBody(config):按 method / withBody 解析请求配置中的 body。
  • resolveResponseData(response, responseType?):按 responseType 解析成功响应体。
  • resolveErrorResponseData(response, responseType?):解析错误响应体(body 只能读一次)。
  • resolveResponseHeader(headers):将 fetch Headers 转为普通对象。
  • resolveAbortSignal(timeout?, signal?):合并外部取消与超时,返回最终 signal 与清理函数。
  • createAxiosError(response, options?):根据 HTTP 错误响应创建 AxiosError
  • createAxiosRequestError(config, err, options?):根据网络/取消/超时错误创建 AxiosError
  • createAxiosBizError(response, options?):根据业务失败响应创建 BizError
  • isHttpOk(status):判断 HTTP 状态码是否为 2xx。
  • ResponseDataParseError:JSON 响应体解析失败时抛出,保留原始 body。

类型

  • Adapter:适配器函数类型 (options: AxiosRequest) => Promise<AxiosResponse>
  • AxiosRequest:请求配置(url/baseURL/method/headers/params/data/adapter/responseType/timeout/signal/...)。
  • AxiosResponse:响应结构(data/status/statusText/headers/config/response)。
  • AxiosError:错误结构(含 isAxiosError/code/config/response/status)。
  • AxiosRequestHeaders:请求头类型(常用头字面量 + 自定义头)。
  • Method:HTTP 方法联合类型。
  • TResponseType:响应体解析类型(json | text | blob | arrayBuffer)。
  • RequestBody:请求体类型。
  • QueryParams:查询参数对象类型。