StorageUtils.ts 2.09 KB
/**
 * 微信存储功能工具
 */

import WxStorage from "../platform/wx/WxStorage";
import Storage from "../platform/Storage";

export default class StorageUtils {
    private store: any = null

    constructor() {
        if (typeof localStorage === 'object')
            this.store = new Storage;

        if (typeof (wx) != "undefined")
            this.store = new WxStorage;
    }

    private __isExpired(entity: any) {
        if (!entity) return true;
        let isExpired = this.timestamp - (entity.timestamp + entity.expiration) >= 0;
        return isExpired;
    }

    get timestamp() {
        return +(new Date().getTime() / 1000).toFixed(0);
    }

    set(key: string, value: Object, expiration = 0) {
        const entity = {
            timestamp: this.timestamp,
            expiration,
            key,
            value
        };
        this.store.setItem(key, JSON.stringify(entity));
        return this;
    }

    get(key: string) {
        let entity: any;
        try {
            entity = this.store.getItem(key);
            if (entity) {
                entity = JSON.parse(entity);
            } else {
                return null;
            }
        } catch (err) {
            console.warn(err);
            return null;
        }

        // 没有设置过期时间, 则直接返回值
        if (!entity.expiration)
            return entity.value;

        // 已过期
        if (this.__isExpired(entity)) {
            this.remove(key);
            return null;
        } else {
            return entity.value;
        }
    }

    remove(key: string) {
        try {
            this.store.removeItem(key);
        } catch (err) {
            console.warn(err);
        }
        return this;
    }

    clear() {
        try {
            this.store.clear();
        } catch (err) {
            console.warn(err);
        }
        return this;
    }

    isExist(key: string): boolean {
        return this.store.hasKey(key);
    }

    private static instance: StorageUtils;
    static get I(): StorageUtils {
        return this.instance || (this.instance = new StorageUtils);
    }
}