storage.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import config from "../model/config"
  2. import dayjs from "dayjs";
  3. const EXSPACE = "ex_space";
  4. const isUp = false;// 升级本地存储 新增过期失效功能 默认不打开 设置为true后生效
  5. export default {
  6. getStorage(space = config.NAMESPACE) {
  7. const res = wx.getStorageSync(space);
  8. return JSON.parse(res || "{}");
  9. },
  10. setItem(key, val, ex) {
  11. const storage = this.getStorage();
  12. storage[key] = val;
  13. if (isUp && ex){
  14. let exObj = this.getStorage(EXSPACE);
  15. exObj[key] = dayjs().valueOf() +ex;
  16. wx.setStorageSync(EXSPACE, JSON.stringify(exObj))
  17. }
  18. wx.setStorageSync(config.NAMESPACE, JSON.stringify(storage))
  19. },
  20. getItem(key) {
  21. const storage = this.getStorage();
  22. const exObj = this.getStorage(EXSPACE);
  23. if (isUp){
  24. if (exObj && exObj[key] && exObj[key] > dayjs().valueOf()){
  25. }else {
  26. this.clearItem(key)
  27. return null;
  28. }
  29. }
  30. return storage[key];
  31. },
  32. clearItem(key) {
  33. const storage = this.getStorage();
  34. delete storage[key]
  35. wx.setStorageSync(config.NAMESPACE, JSON.stringify(storage))
  36. },
  37. clearAll() {
  38. wx.removeStorageSync(config.NAMESPACE)
  39. }
  40. }