Interface data persistence scheme

background

In a project, a large amount of configuration data is requested through the interface to render the page dynamically, and in most cases the configuration data does not change. If you wait for the interface to return and then start rendering, you will waste the user’s waiting time. Hence the project — interface data localization cache.

The principle of

  1. throughindexedDBCaches interface data for each request.
  2. If cached data is found before the interface is requested, the cached data is read first. After the interface is updated, the page is updated and the database is updated.

Generalize this solution as an SDK

The SDK exposes only one method that needs to be called to intercept and cache the interface. You can understand this method as a request method that comes with an interceptor.

  1. Method 1: Supports incomingAxiosRequestConfig, AxiosInstance(Request parameters, request instance), automatically cache the current interface.
  2. Method 2: Support incoming custom request (Promise type), automatically intercept this Promise, and cache data.
  3. Supports an incoming callback method to filter incoming and outgoing parameters of an interface, or to control whether caching is required.

use

import IDB from 'axios-indexeddb-sdk'
const md5 = require('md5')
/ / initialization
const isRealData = ({data}) = > data.code === '200' // When is the stored data valid and the database is not read if the stored data is found to be invalid
const idb = new IDB({appKey: 'testAppKey'})
// Approach 1: pass in request parameters, automatically cache interface data and respond to data (proxy AXIOS approach)
idb.httpWithIDB({
  DbHttp: axios, // Pass in an axios instance
  fetchKey: md5(JSON.stringify({param1: '123'})), // Request unique key: Use MD5 to issue the unique key used to generate the request
  funName: 'myFunName'.axiosRequestConfig: {
    method: 'get'.url: 'xx/xx'.params: {param1: '123'}},newDataCb: (data) = > {
    console.log('Changed data, return changed data', data)
  }
}).then(res= > {
  console.log('Return cached data, or request data if no cached data', res)
})
// Mode 2: the custom request mode is passed in, which intercepts the request and caches the request result
idb.httpWithIDB({
  fetchKey: '1641379655454'.// The unique key of the request
  funName: '610b9447c82fed7a0c87d245'.// The method name of the request
  fetchPromise: myFetch, // Promise
      
       , not implemented, please construct request Promise yourself
      
  newDataCb: (data) = > {
    console.log('Changed data, return changed data', data)
  }
}).then(res= > {
  console.log('Return cached data, or request data if no cached data', res)
})
Copy the code

demo

1. Demo1: Hosting axios requests to SDK: github.com/wuweikd/axi…

2. Demo2, incoming request to SDK, auto racing callback: github.com/wuweikd/axi…

Warehouse address: github.com/wuweikd/axi…

Kurt: www.npmjs.com/package/axi…