uniapp 本地缓存带 过期时间戳 功能

const api = {
    baseUrl: 'https://127.0.0.1:3000',
    /**
   * @param {缓存key} key
   * @param {需要存储的缓存值} value
   * @param {过期时间,默认0表示永久有效} expire
   */
    setCache(key, value, expire = 0) {
        let obj = {
            data: value, //存储的数据
            time: parseInt(Date.now() / 1000), //记录存储的时间戳
            expire: expire //记录过期时间,单位秒
        }
        uni.setStorageSync(key, JSON.stringify(obj))
    },
    /**
     * @param {缓存key} key
     */
    getCache(key) {
        let val = uni.getStorageSync(key)
        if (!val) {
            return null
        }
        val = JSON.parse(val)
        if (val.expire && Date.now() / 1000 - val.time > val.expire) {
            uni.removeStorageSync(key)
            return null
        }
        return val.data
    },
    // 获取 access_token
    getAccessToken: function () {
        
        return new Promise((resolve, reject) => {
            //判断缓存是否存在
            if (api.getCache('access_token')) {
                resolve(api.getCache('access_token'));
            }else{
                let that = this;
                uni.request({
                    url: that.baseUrl + '/api/getAccessToken',
                    method: 'post',
                    success: function (atRes) {
                        if (atRes.data.code == 200) {
                            api.setCache('access_token', atRes.data.data.access_token, atRes.data.data.expires_in-100)
                            resolve(atRes.data.data);
                        } else {
                            resolve(0);
                        }
                    }
                });
            }
            
        })
    },
    
}
export default api;