0.0.20 • Published 4 years ago

@forchange/apis v0.0.20

Weekly downloads
1
License
MIT
Repository
-
Last release
4 years ago

apis

npm version license

基于 axios 封装的接口管理方案,@forchange/apis

Features

  • 接口统一管理
  • 可配置多个接口服务
  • 支持 restful 接口
  • 支持命名空间

Installing

$ npm install @forchange/apis

Syntax

new Apis(serverMap, apiMap);

Parameters

serverMap

  • serverMap 是服务配置的 map 对象
  • 服务的参数配置同 axios 中的 config 部分
  • default 为自定义属性,当 default 为 true 时,api 会使用它做为默认服务配置
{
  "baseServer": {
    "default": true,
    "baseUrl": "https://base.apis.com"
  }
}

apiMap

  • apiMap 是接口配置的 map 对象
  • 接口的参数配置同 axios 中的 config 部分,会覆盖服务配置中的参数
  • server 为自定义属性,表示使用哪个服务配置,当 server 为 null 时,表示使用默认服务配置
{
  "getBaseInfo": {
    "method": "get",
    "url": "/info"
  }
}

Custom

rest:restful 参数

当接口中需要传递 restful 参数时,按如下配置

配置时用:标记:

{
  "getBaseInfoId": {
    "method": "get",
    "url": "/info/:id"
  }
}

调用时参数中添加 rest 参数:

apis.getBaseInfoId({
  rest: {
    id: 1
  }
});

Namespace

^0.0.16 起支持

apiMap 的 key 中出现的 / 会解析为对应的命名空间路径,不需要命名空间时,不加 / 即可

e.g: auth/user/getInfo => auth.user.getInfo()
{
  'user/getInfo':{
    method: "get"
    server: "baseServer"
    url: "/user/info"
  }
}

=> apis.user.getInfo()

Interceptors

Apis 通过useReq,useRes两个接口对请求做拦截,可以多次调用,添加多个 middleware

Apis.useReq(middleware)

axios.interceptors.request.use

Apis.useReq(function(config) {
  config.headers.Authorization = "Bearer";
  return config;
});

Apis.useRes(middleware)

axios.interceptors.response.use

Apis.useRes(function(res) {
  res.msg = "ok";
  return res;
});

Usage

const apis = new Apis(serverMap, apiMap);

apis.getTest({
  params: {
    color: "green"
  }
});

License

MIT

0.0.20

4 years ago

0.0.19

4 years ago

0.0.18

4 years ago

0.0.17

5 years ago

0.0.16

5 years ago

0.0.15

5 years ago

0.0.14

5 years ago

0.0.13

5 years ago

0.0.12

5 years ago

0.0.11

5 years ago

0.0.10

5 years ago

0.0.9

5 years ago

0.0.8

5 years ago

0.0.7

5 years ago

0.0.6

5 years ago

0.0.5

5 years ago

0.0.4

5 years ago

0.0.3

5 years ago

0.0.2

5 years ago

0.0.1

5 years ago