123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134 |
- class Cache {
- constructor(handler) {
- this.cacheSetHandler = uni.setStorageSync;
- this.cacheGetHandler = uni.getStorageSync;
- this.cacheClearHandler = uni.removeStorageSync;
- this.cacheExpire = '_expire_2019_12_17_18_44';
- }
-
- time() {
- return Math.round(new Date() / 1000);
- }
-
- setExpireCahe(key, expire) {
- expire = expire !== undefined ? expire : 0;
- if (expire) {
- this.cacheSetHandler(key + this.cacheExpire, this.time() + expire)
- }
- }
-
- getExpireCahe(key, $bool) {
- try {
- let time = this.cacheGetHandler(key + this.cacheExpire);
- if (time) {
- let newTime = parseInt(time);
- if (time && time < this.time() && !Number.isNaN(newTime)) {
- if ($bool === undefined || $bool === true) {
- this.cacheClearHandler(key);
- this.cacheClearHandler(key + this.cacheExpire);
- }
- return false;
- } else
- return true;
- } else {
- return !!this.cacheGetHandler(key);
- }
- } catch (e) {
- return false;
- }
- }
-
- set(key, data, expire) {
- if (typeof data === 'object')
- data = JSON.stringify(data);
- try {
- this.setExpireCahe(key, expire);
- return this.cacheSetHandler(key, data);
- } catch (e) {
- return false;
- }
- }
-
- has(key) {
- return this.getExpireCahe(key);
- }
-
- get(key, $default, expire) {
- try {
- let isBe = this.getExpireCahe(key);
- let data = this.cacheGetHandler(key);
- if (data && isBe) {
- if (typeof $default === 'boolean')
- return JSON.parse(data);
- else
- return data;
- } else {
- if (typeof $default === 'function') {
- let value = $default();
- this.set(key, value, expire);
- return value;
- } else {
- this.set(key, $default, expire);
- return $default;
- }
- }
- } catch (e) {
- return null;
- }
- }
-
- clear(key) {
- try {
- let cahceValue = this.cacheGetHandler(key + this.cacheExpire);
- if (cahceValue)
- this.cacheClearHandler(key + this.cacheExpire);
- return this.cacheClearHandler(key);
- } catch (e) {
- return false;
- }
- }
-
- clearOverdue() {
-
-
-
-
-
-
- }
- }
- export default new Cache;
|