http-schema: 一个配置化的项目API管理库/Schema-First Http Library

用配置化的方式去管理项目的 api,可以方便的与 react-query 等库结合
更新于: 2024-02-23 22:41:34
项目主页: https://github.com/afeiship/http-packages

快速使用

npx @jswork/http-schema-init

简介

Schema-First Http Library, httpSchema是一个基于 JavaScript 的库,用于定义和生成API请求。它可以使用不同的 HTTP客户端,例如 AxiosFetch ,以便根据您的项目需求进行定制。

灵感

  • 项目实践过程中改进: api 应该是 schema 化的,大量重复应该被 schema
  • ROR: rails 的 routes 生成 → resource/only/excpet 关键词

安装

  • browser 与 bun 环境自带 fetch
  • nodejs 默认没有 fetch
yarn add @jswork/http-schema
环境安装(对应环境下的 HttpClient/adapter)备注
浏览器-axios
yarn add axios @jswork/next-axios
公司web项目首选
浏览器-fetch
yarn add @jswork/next-fetch
次级选择
nodejs
yarn add @jswork/next-fetch node-fetch@2.6.7 form-data
 
bun
yarn add @jswork/next-fetch
 
uniapp3 小程序
yarn add @jswork/next-uniapp-request
微信小程序推荐

简单使用

  • axios 配合,默认
  • fetch 配合使用
import httpSchema from '@jswork/http-schema';

// use Axios
const $api1 = httpSchema({
  baseURL: "https://api.github.com",
  request: ["", "json"],
  resources: [
  	'options',
    {
      host: "http://dev2.demo.com",
      prefix: "v1_",
      name: "users",
      only: ["index"],
    },
    { prefix: "v2_", name: "posts" },
    { name: "roles", except: ["destroy"] },
    { name:'tags'},
    { name:'categories'},
    { name:'pictures'},
  ],
  items: [
    {
      items: {
        login: ["get", "/users/afeiship"],
      },
    },
  ],
});

需要改进的点

  1.  mix 拦截: 会同时处理 $name === xxx  的 request/response
  2. 边缘拦截: 排在第1个的,放在最后一个的 interceptor
  3. 与 nx.to 的集成,在配置阶段,优化 try/catch 对 error 的处理
  4. $error: 通用错误 msg/code 的实现
  5. 当我们有一个API是由某几个API组合而成的新的API的情况,提供一种解决方案

参考