Wechat applet request encapsulation (request)

Keywords: Front-end JSON

When I started to write an applet, I was quite helpless with the request API of the applet request interface, because I didn't think so much about the urgency of the project, so I started directly. Later, I considered to make a package for unified data processing to reduce development repeatability and optimize code.

First, I encapsulate a class:

import { base_url } from '../config/api' // Introduce the ip of our interface, and then we only need to pass in the api.

const tips = {
    1: 'Sorry, there was an error',
    1005: 'appkey Invalid, request error',
    3000: 'No authority',
    ...
} // Multiple error handling strings


----------


export default class HTTP {
    fetch (params) {
        const {
                url,
                method = 'GET',
                data = {},
                success
              } = params                            // es6 object deconstruction request is the successful processing of transfer and participation we need
              
        wx.request({
            url: base_url + url,
            method,
            data,
            header: {
              'Content-Type': 'application/json'
            },
            success: res => {
                const { code } = res.data
                
                if (code === 0) {                  // Successful judgment of the agreement with the backstage
                    success && success(res.data)   // Successful callback
                    return
                }
                
                const { error_code } = res.data
                this._show_error(error_code)       // Failed processing, pop up prompt box
            },
            fail: err => {
                this._show_error(1)                // Failed processing, pop up prompt box
            }
        })
    }
    
    _show_error (error_code = 1) {
        const tip = tips[error_code]
        
        wx.showToast({
            title: tip ? tip : tips[1],
            icon: 'none',
            duration: 2000
        })
    }
}

Here, we have made a simple basic encapsulation, but we also have to do the corresponding processing from the callback. If we need a variable to get the data of this request directly, we need to use promise and async await for processing. The code is as follows:

import { base_url } from '../config/api' // Introduce the ip of our interface, and then we only need to pass in the api.

const tips = {
    1: 'Sorry, there was an error',
    1005: 'appkey Invalid, request error',
    3000: 'No authority',
    ...
} // Multiple error handling strings

export default class HTTP {
    fetch (params) {
      return new Promise((resolve, reject) => {
         const {
                url,
                method = 'GET',
                data = {},
                success
              } = params                            // es6 object deconstruction request is the successful processing of transfer and participation we need
              
         wx.showLoading('Loading')    
              
         wx.request({
            url: base_url + url,
            method,
            data,
            header: {
              'Content-Type': 'application/json'
            },
            success: res => {
                const {
                    data = {},                     // data is an object by default
                    data : { code, msg }
                } = res
                
                if (code === 0) {                  // Successful judgment of the agreement with the backstage
                    wx.showToast({ title: msg })
                    resolve([null, _data])         // Successful callback
                    return
                }
                
                const { error_code } = res.data
                this._show_error(error_code)       // Failed processing, pop up prompt box
                reject([data])                     // Failed callback and exposed data
            },
            fail: err => {
                this._show_error(1)                // Failed processing, pop up prompt box
                reject([{msg = 'Request error'}])                     // Failure handling
            },
            complete: () => {
                wx.hideLoading('Loading')
            }
        }).catch(err => err)
      }
   })
        
    
    _show_error (error_code = 1) {
        const tip = tips[error_code]
        
        wx.showToast({
            title: tip ? tip : tips[1],
            icon: 'none',
            duration: 2000
        })
    }
}

Then we directly use async and await when calling:

import HTTP from '../util/HTTP '
import api from '../api'  // Import interface

class Model extends HTTP {
    async search (data) {
        const [err, res] = await this.Fetch({
          url: api,
          data
        })
        
     if(err){
         //Corresponding processing of failure
         return
     }
     
     // Successful corresponding processing
  }
}

If you don't use inheritance, then it's the same way to directly instantiate HTTP and get fetch.
I hope you can put forward positive suggestions. If you have any questions, please contact me.

Posted by hasek522 on Thu, 31 Oct 2019 18:49:47 -0700