Indexeddb-based caching solution

Reference documents: wangdoc.com/javascript/…

Abstract

It was found that localStorage could only store 5~ 10MB of data, while indexedDB could store 250MB of data. However, localStorage is synchronous and indexedDB is asynchronous, so there is no way to solve the problem. After searching online, there is no better package for indexedDB, so I had to write one myself and publish it to NPM and Github. If you are interested, you can check it out, click on a star or make an issue if you have an idea.

Open source address

Github.com/zmkwjx/baik…

www.npmjs.com/package/@ba…

Introduction to indexedDB

As the capabilities of the browser continue to increase, more and more sites are considering storing large amounts of data on the client side, which can reduce the amount of data retrieved from the server and bring it directly from the local.

Existing browser data storage schemes are not suitable for storing large amounts of data: cookies are less than 4KB in size, and each request is sent back to the server; LocalStorage is between 2.5MB and 10MB (depending on the browser), does not provide search, and cannot create custom indexes. So a new solution was needed, and this was the context in which IndexedDB was born.

In plain English, an IndexedDB is a browser-provided local database that can be created and manipulated by web scripts. IndexedDB allows you to store large amounts of data, provide a lookup interface, and build indexes. These are all things that LocalStorage does not have. In terms of database type, IndexedDB is not a relational database (it does not support SQL query statements) and is closer to a NoSQL database.

IndexedDB has the following characteristics.

(1) Key-value pair storage. IndexedDB uses an object Store internally to store data. All types of data can be stored directly, including JavaScript objects. In the object warehouse, data is stored as “key-value pairs”, and each data record has a corresponding primary key. The primary key is unique and cannot be duplicated, otherwise an error will be thrown.

(2) asynchronous. IndexedDB does not lock the browser and users can still perform other operations, in contrast to LocalStorage, where operations are synchronous. Asynchronous design is designed to prevent massive data reads and writes from slowing down the performance of a web page.

(3) Support transactions. IndexedDB supports transaction, which means that if one of a series of steps fails, the entire transaction is cancelled and the database is rolled back to the state before the transaction occurred, without overwriting only a portion of the data.

(4) Homologous restriction. IndexedDB is subject to the same origin restriction, with each database corresponding to the domain name that created it. Web pages can only access databases under their own domain names, but not cross-domain databases.

(5) Large storage space. IndexedDB has much more storage space than LocalStorage, usually no less than 250MB or even no upper limit.

(6) Support binary storage. IndexedDB can store not only strings but also binary data (ArrayBuffer objects and Blob objects).

@baikbingo/ Cache package use

Get objects and configurations

The installation

npm i @baikbingo/cache -S
Copy the code

This package (cache) can support vue.use or encapsulate the function itself without directly fetching the instance.

import cache from "@baikbingo/cache"; import Vue from "vue"; Vue.use(cache); // import {createCache} from "@baikbingo/cache"; app.prototype.$cache = createCache();Copy the code

It is recommended to use the cache hook function createCache.

import { createCache } from "@baikbingo/cache"; Const cahce = createCache({databaseName: "cache", // tableName: "localStorage", // tableName version: 1 // version number}); export default cahce;Copy the code

Fetch cache operation

For each set operation, the cache puts data into memory. For initialization, get or syncGet can be used to retrieve data

const cahce = createCache(); // Async cache.get(key). Then (res => {console.log(" result ", res); }); // sync const res = cache.syncget (key);Copy the code

What if it is a refresh operation and set is not executed? First, the function calls the readAll method internally to fetch data from the indexedDB, but this operation is asynchronous, so there is no guarantee that the browser will fetch data from memory using syncGet. Or if your operation is asynchronous, you can use the get method (which reads the data directly and retrieves the data in indexedDB if it is not in memory).

ReadAll = readAll; readAll = readAll; Cache.readall (). Then (() => {const res = cache.syncget (key); }); // or await cache.readall (); const res = cache.syncGet(key);Copy the code

What if you combine it with store? ReadAll can be performed at route guard or when the instance is first mounted, such as vuex:

export default {
  create() {
    cache.readAll().then(() => {
      this.$store.state.token = cache.syncGet("token")
    })
  }
}
Copy the code

More asynchronous operations

const cahce = createCache();
cache.set(key, value);
cache.del(key);
cache.clear();
Copy the code

More Synchronous operations

const cahce = createCache();
cache.syncSet(key, value);
cache.syncDel(key);
cache.syncClear();
Copy the code