Straight into the theme

A little wheel for interface redundancy

npm i box-cat

The story background

Every time you see a back-end management project, you’ll see a list of these functions:

functionPostCommodity (data){} // Add commodityfunctionGetCommodityList (data){} // Get the list of commoditiesfunctionGetCommodityDetail (id){} // Get commodity detailsfunctionPutCommodity (id, data){} // Modify commodity detailsfunctionPutCommodityStatus (id, status){functionDeleteCommodity (id){} // Delete goodsCopy the code

The above encapsulation function and structure is similar, but each time to manually more than one to one encapsulation function, code redundancy.

So I wonder if I can use a JSON form to automatically generate the interface function

Train of thought

// store. Js // Interface object formatexport default {
    postCommodity: 'api/commodity',
    getCommodityList: 'api/commodity/list',
    getCommodityDetail: 'api/commodity/:id',
    putCommodity: 'api/commodity/:id',
    putCommodityStatus: 'api/commodity/:id/:status',
    deleteCommodity: 'api/commodity/:id',}Copy the code
  • Each field generates a request interface function named key, and the convention is to perform methods matching in the key as the internal request mode (GET, POST).
  • Use the re to cut out the param path parameters and use the call parameters instead of param to make the request. To make it easier to pass parameters, when there is only one param parameter, we just need to getCommodityDetail(1). When there are more than one, we need to getCommodityDetail
{id: 1}} putCommodityStatus({id: 1, status: 0})Copy the code
  • Of course, we are based on HTTP request library encapsulation layer, so we need to generate the request interface function, pass an Axios or flyio library, support get, post… Request method.
  • * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
// flyio
getCommodityList({
    page: 1,
    limit: 10
})
// axios
getCommodityList({
    params: {
        page: 1,
        limit: 10}})Copy the code

Generate the corresponding method internally by matching method (get, POST) in key

// Generate import store from for functions that encapsulate store on fetch'store'
import { createApis } from 'box-cat'
const http = createApis(store, fetch)
http.getCommodityList({
    page: 1,
    limit10}) :Copy the code

This is a traversal generation process, which can be costly in performance if interfaces are not needed or not yet used. Therefore, es6 proxy can be used to fill this pain point.

// Return the Proxy instance, lazily generating the interface method. CreateApi import {createProxy} from is gracefully degraded when a proxy is not supported'box-cat'
const http = createProxy(store, fetch)
Copy the code

Curtain call

Writing catch chicken, hope to help you, more usage please click the following link

Github.com/hengshanMWC…