Using local storage as timing cache

background When the page uses ajax to get the data, it will send a request to the server to get the data every time it visits, however Some data updat...

background

When the page uses ajax to get the data, it will send a request to the server to get the data every time it visits, however Some data updates are not frequent, so I want to use localStorage for local storage, and then update data at fixed intervals. (download address: https://gitee.com/whnba/data_storage)

Structural design

expires: used to save data expiration time

Data: used to save data

{ expires: "Due time" data:"data" }

Set cache data

Use JSON to serialize and save the data structure. If the data is full, clear it all. What else

static set(key, value, expires = 3600) { const date = new Date(); try { localStorage.setItem(key, JSON.stringify({ expires: date.valueOf() + expires * 1000, data: value })); } catch (e) { if (e.name === 'QuotaExceededError') { console.log("Data full, auto clear"); Cache.clear(); Cache.set(key, value, expires); } } }

Get cached data

First, judge whether the data is due. If it is not, return the data. Otherwise, delete it.

static get(key) { const result = JSON.parse(localStorage.getItem(key)); const date = new Date(); if (result && result.expires > date) { return result.data; } else { Cache.remove(key); return null; } }

Complete code

/** * Data cache */ class Cache { /** * Get cache * @param key * @return */ static get(key) { const result = JSON.parse(localStorage.getItem(key)); const date = new Date(); if (result && result.expires > date) { return result.data; } else { Cache.remove(key); return null; } } /** * Set cache * @param key Key name * @param value Cache data * @param expires Expiration time unit s */ static set(key, value, expires = 3600) { const date = new Date(); try { localStorage.setItem(key, JSON.stringify({ expires: date.valueOf() + expires * 1000, data: value })); } catch (e) { if (e.name === 'QuotaExceededError') { console.log("Data full, auto clear"); Cache.clear(); Cache.set(key, value, expires); } } } /** * Delete key * @param key */ static remove(key) { localStorage.removeItem(key); } /** * empty */ static clear() { localStorage.clear(); } } export default Cache;

6 November 2019, 15:54 | Views: 4550

Add new comment

For adding a comment, please log in
or create account

0 comments