Vue api creator

An api manager bases on Vue

Version: 2.0.5 Updated: 12/18/2019

By: msidolphin

Downloads Last 30 Days: 137

vue-api-creator

Build Status Coverage Status codebeat badge

An api manager bases on axios

中文文档

Usage

Install

npm install vue-api-creator -S
import api from './api'
import ApiCreator from 'vue-api-creator'

Vue.use(ApiCreator, {
  baseURL: '/baseURL'
  modules: api,
  // Response fails if response status is in this list
  permanentErrors: [404, 415, 500, 501, 429],
  beforeRequest (options) {
    console.log(options)
  },
  afterRequest (res) {
    console.log(res)
  },
  onError (err) {
    if (err.isInternalError) {
      console.log('An exception has occurred on your network')
    } else {
      console.log('An error response from server')
    }
  },
  mock: 'https://www.xxxx.com'
})

Use

export default {
    created () {
        this.$api('app/list').then(res => {
            // ....
        }).catch(err => {
            // ....
        })
    }
}

Api directory

├──  api
│    │── app
│    │    ├── index.js
│    └── index.js   

app/index.js

export default {
    BASE_URL: '/sys/app',
    api: [
      {
        name: 'list',
        desc: 'get apps',
        method: 'GET',
        path: 'list',
        mock: true // enable mock
      }
    ]
}

api/index.js

import app from './app'

export default {
    app
}

Server Response Structure

Your server response body shoule be like this:

{
  code: Number, // status code
  success: Boolean, // whether the response was successful 
  msg: String, // response message
  data: <T> // response data
}

Configuration

ApiCreator config

  • baseURL: The base URL of the request. (String or Function)
  • modules: Api modules.
  • axios: axios instance.
  • enableEncodeURIComponent: encodes characters using EncodeURIComponent.
  • permanentErrors: Response fails if response status is in this list, default: [404, 415, 500, 501, 429].
  • beforeRequest: Called before the request is sent.
  • afterRequest: Called after the request was received.
  • onError: An error occurred during send request or server response, eg: status code in permanentErrors, the request was made but no response was received...
  • mock: The base URL of the mock server.

Api config

  • name: It is api's name.
  • desc: The description of the api.
  • method: The request method to be used when making the request.
  • path: It is the server URL that will be used for the request.
  • mock: Enable mock to the request.
  • params: query params (Array or Boolean). eg: params: ['id', 'name'] => /api/xxxx?id=1&name=2
  • body: body params (Array or Boolean). eg: body: ['ids', 'names'] => {ids: [1], names: ['a', 'b']}
  • responseType: response type. accepted values: ['', 'arraybuffer', 'blob', 'document', 'json', 'text']. default: json

License

MIT

Copyright © 2019, msidolphin

Categories: Vue js
Tags: