1.0.3 • Published 4 years ago

axios-restful-api v1.0.3

Weekly downloads
-
License
ISC
Repository
-
Last release
4 years ago

axios-restful-api

Axios 作为一个基于 promise 的 HTTP 库,被广泛应用在浏览器和 node.js 中。在 vue 项目的开发中,我们经常需要对 axios 进行二次封装,以便管理越来越多 rest 风格的请求接口。axios-restful-api 旨在简化这个封装使用的过程,做到即开即用。

安装

npm install axios-restful-api

配置

这里我们假设项目中有两个模块 foobar,分别需要他们的CRUD方法

// main.js
import Vue from 'vue';
import RestApi from 'axios-restful-api';

Vue.use(RestApi, {
  foo: 'http://example.com/api/v1/foo',
  bar: 'http://example.com/api/v1/bar',
});

new Vue({
  render: (h) => h(App),
}).$mount('#app');

此时会分别生成5个rest风格的api请求方法到 Vue.prototype.$api.fooVue.prototype.$api.bar 下,分别是 findOne 获取单数据详情、findAll 获取列表、create 创建、update 更新、delete 删除。

使用

GET https://example.com/foo/888?a=1&b=2

const id = 888;
const query = { a: 1, b: 2 };
this.$api.foo.findOne(id, query).then(() => {
  // TODO
});

GET https://example.com/foo?a=1&b=2

const query = { a: 1, b: 2 };
this.$api.foo.findAll(query).then(() => {
  // TODO
});

POST https://example.com/foo

{ name: 'qiubozhang' }

const params = { name: 'qiubozhang' };
this.$api.foo.create(params).then(() => {
  // TODO
});

PUT https://example.com/foo/888

{ name: 'qiubaizhang' }

const id = 888;
const params = { name: 'qiubaizhang' };
this.$api.foo.update(id, params).then(() => {
  // TODO
});

DELETE https://example.com/foo/888

const id = 888;
this.$api.foo.delete(id).then(() => {
  // TODO
});

自定义方法

有时候项目中会有不符合 restful api 出现,可以在引入的时候进行自定义

// main.js
Vue.use(RestApi, {
  url: 'http://example.com/api/v1/foo',
  // 自定义方法
  customMethod(params) {
    return this.request({
      url: 'http://example.com/api/v1/foo/custom',
      method: 'post',
      params,
    }),
  },
});

使用的时候与其他基础方法一致

this.$api.customMethod({ foo: bar }).then((res) => {
  // TODO
});

这样做会使 main.js 文件过于庞大,推荐抽离成单个文件后引入使用。另外,request 是 axios 实例的单例包装。详情看这里

单模块

支持单个模块的配置方式,在某些测试场景下可以快速开发

Vue.use(RestApi, 'http://example.com/api/v1/foo/bar');

使用和多模块一致

this.$api.findOne(id).then((res) => {
  // TODO
});

全局配置项

Vue.use(RestApi, {
  user: '/users',
  books: '/books',
  config: {
    timeout: 2000,
    baseURL: 'http://example.com/api/v1',
    headers: { 'foo': 'bar' },
    // 请求拦截器
    requestInterceptor: [
      (config) => Promise.resolve(config),
      (error) => Promise.reject(error),
    ],
    // 响应拦截器
    responseInterceptor: [
      (response) => Promise.resolve(response),
      (error) => Promise.reject(error),
    ],
  },
});

request

axios 实例包装,接收一个对象,对象属性如下

参数说明类型可选值默认值
method请求方法string-[]
url请求地址string-[]
rParamsurl中嵌入的id类参数object-{}
query路由参数object-{}
params请求体参数object-{}
options兼容axios请求配置object-{}
1.0.3

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago