About encapsulation of applet network requests (detailed version)

Guide readers from the most basic applet network request encapsulation to the optimal solution of network request encapsulation

When using the native applet network api, there are two disadvantages:

  1. Multiple pages often send multiple network requests on behalf of the server, which puts too much pressure on the server - > depressurize
  2. Based on reason 1, to prevent the official abandonment of wechat in the future wx.request Duplicate operations caused by changing this api to another one - > reduce dependency and prevent duplication

1. wx native network request

Wechat native request seems very clear, but the functions of success and failure are wx.request Internally, if readers have some knowledge of jQuery, they will find it very similar to jQuery:

But this method is on the verge of extinction. Next, we use promise to encapsulate the native network requests of wechat layer by layer

2. Simple packaging

//  ../../request/one.js
export default function reqeust(params) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: params.url,
      method: params.method || 'get',
      data: params.data || {},
      success: res => {
        resolve(res)
      },
      fail: err => {
        reject(err)
      }
    })
  })
}

If you know pomise well, you can also use the evolution version:

//  ../../request/one.js
export default function reqeust(params) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: params.url,
      method: params.method || 'get',
      data: params.data || {},
      success: resolve,
      fail: reject
    })
  })
}

Use in page:

//In page import
 import reqeust from '../../request/one.js'
// Used in the onload function of the page
  onLoad: function () {
    reqeust({
      url: 'https://xxxxxxxxxxxxxxxxxxxxxxxxxxx',
    })
      .then(res => {
      console.log(res)
    })
      .catch(err => console.log(err))
  }                    

It turns out the same thing

3. Evolution package

Review the import and export knowledge of es6:

// Constant export
//public.js
const demo = 'use export Exported constant,The constant cannot be renamed,Brace required';
export {
  demo 
}
//Import of constants
//getdemo.js
import { demo } from './public'
console.log(demo ) // 'constant exported by export, cannot be renamed, braces are required'
//Function export and import
//Function export
//fn.js
export function fn() {
  console.log("use export Exported fn,This function cannot be renamed,Brace required")
}
//Function import
//getFn.js
import { fn } from './fn.js'
fn(); // "The function cannot be renamed with fn exported by export, and braces are required"

//Export and import all
//export
//allData.js
export default function allData() {
console.log("use export default Exported data,You can rename the function,Braces are not required")
}
//getAllData.js
//Import
 import reName_AllData from './allData.js'
reName_AllData()//Data exported with export default can be renamed without braces

Suppose a part of the requested url is the same

  • The url is divided into two parts: the first part is the public request address, which is separated into a file separately, and the other part is the network address PageUrl requested by a single page
  • stay requers.js Add the public request address public url to the url
  • Page import request.js Initiate a request
//Extract public url to separate file
//publicData.js
const baseURL = 'https://jiazhuang/zheshi/yige/gonggongurl';
export {
  baseURL
}
//Encapsulated network request file, import the above file
//network1-0.js
import { baseURL } from './public'
export function request(params) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: baseURL + params.url,
      method: params.method || 'get',
      data: params.data || {},
      success: resolve,
      fail: reject
    });
  })
}
//Only fill in the corresponding network address when using the page
//Page import encapsulated network1-0.js
import { request } from '../../req/newwork1-5'
//Used in onLoad function
 onLoad: function () {
    request({
      url: 'public/v1/home/swiperdata'
    }).then(res => {
      console.log(res)
    })
      .catch(err => console.log(err))
  }

This is the second layer of packaging

But this is not convenient:
There are too many requests to be sent for a single page, and the readability of the code is not good
Then there's the ultimate package:

4. Evolution package

In this step, we aim at layering:

Based on the page hierarchy, encapsulating the request that a single page needs to send as a file getPage.js from page.js Responsible for request.js Send the real network request, and all the page has to do is call page.js Single request method in
The following is an illustration:


Explanation:

  1. request.js Responsible for integrating public api with getPage.js The api passed in is spliced to send data to the background after integration
  2. getPage.js Up responsible for up request.js Send request, down as send request function waiting to be called, function internal storage non-public api
  3. Page as page, only call getPage.js Internal functions

Example of whole performance

//publicData.js  As a common part of the api
 const baseUrl= 'https://jiazhuang-shiyige-api/api/';
export {
  baseUrl
}

//request.js  As the file that actually sends the network request
import { publicUrl } from './publicData'
export default function reqeust(params) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: publicUrl + params.url,
      method: params.method || 'get',
      data: params.data || {},
      success: resolve,
      fail: reject
    })
  })
}

// getIndexData.js  : responsible for calling up request.js , which is responsible for all functions of sending network requests to the page. The internal part of the function stores the request address of the non-public part
import reqeust from './request'
export function getBannerData() {
  return reqeust({
    url: 'wo/zhen-de/shi/api/banner',
  })
}
//The index page import belongs to getIndexData.js , calling the method of the page in the onload function
import { getBannerData} from '../../request/getIndexData'
onload(){
  getBannerData().then(res => {
      console.log(res)
      //Here you can operate on the data
    }).catch(err => console.log(err))
}

In this example, the process is explained step by step, maybe with some redundancy, but these are more in line with the standardization. The page page does not care about sending network requests, but is only responsible for calling, getPageData.js Only responsible for sending the corresponding url to request.js Processing, and request.js It is responsible for splicing and integrating URLs and others, and finally sending network requests. If you want, you can subdivide a single page, Everything is done to serve development

The above is to package the native network request of the applet step by step to reach the optimal solution

Keywords: network JQuery

Added by harrylt on Tue, 19 May 2020 15:27:11 +0300