http-schema: 一个配置化的项目API管理库/Schema-First Http Library
用配置化的方式去管理项目的 api,可以方便的与 react-query 等库结合
项目主页: https://github.com/afeiship/http-packages
快速使用
npx @jswork/http-schema-init简介
Schema-First Http Library,
httpSchema是一个基于JavaScript的库,用于定义和生成API请求。它可以使用不同的HTTP客户端,例如Axios或Fetch,以便根据您的项目需求进行定制。
灵感
- 项目实践过程中改进: api 应该是
schema化的,大量重复应该被schema化 - ROR: rails 的 routes 生成 →
resource/only/excpet关键词
安装
- browser 与 bun 环境自带 fetch
- nodejs 默认没有 fetch
yarn add @jswork/http-schema| 环境 | 安装(对应环境下的 HttpClient/adapter) | 备注 |
|---|---|---|
| 浏览器-axios | | 公司web项目首选 |
| 浏览器-fetch | | 次级选择 |
| nodejs | | |
| bun | | |
| uniapp3 小程序 | | 微信小程序推荐 |
简单使用
- 与
axios配合,默认 - 与
fetch配合使用
import httpSchema from '@jswork/http-schema';
// use Axios
const $api1 = httpSchema({
baseURL: "https://api.github.com",
// baseURL: location.origin,
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"],
},
},
],
});更新版 resources
// usage.ts
import { ApiResourceNormalizer } from './src/ApiResourceNormalizer';
const normalizer = new ApiResourceNormalizer('rails');
const result = normalizer.normalize([
'posts',
'/sys/super/backend/params',
'/sys/super/backend/adminUsers',
['admin_roles', '/sys/super/backend/adminRole'],
{ name: 'orders', only: ['index', 'show', 'cancel'] },
{ name: 'users', only: ['*', 'disable', 'enable'] },
{ name: 'roles', only: ['index', 'show'] },
{ name: 'permissions', subpath: '/sys/super/backend/imc' },
{ name: 'team_members', resName: 'imcTeamMember', subpath: '/sys/super/backend/imc' },
]);
console.log(result.items);需要改进的点
- mix 拦截: 会同时处理
$name === xxx的 request/response - 边缘拦截: 排在第1个的,放在最后一个的 interceptor
- 与 nx.to 的集成,在配置阶段,优化 try/catch 对 error 的处理
$error: 通用错误 msg/code 的实现- 当我们有一个API是由某几个API组合而成的新的API的情况,提供一种解决方案