cache.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. const postfix = '_cache_time'; // 缓存前缀
  2. const simpleCache = {
  3. postfix: postfix,
  4. }
  5. /**
  6. * 写入缓存
  7. * @param {String} key 本地缓存中的指定的key
  8. * @param {Any} data 需要存储的内容,只支持原生类型、及能够通过 JSON.stringify 序列化的对象
  9. * @param {Number} time 保存的时间, 数字类型,单位秒 为空则永久有效.
  10. */
  11. simpleCache.put = function(key, data, time) {
  12. uni.setStorageSync(key, data)
  13. var seconds = parseInt(time);
  14. if (seconds > 0) {
  15. var timestamp = Date.parse(new Date());
  16. timestamp = timestamp / 1000 + seconds;
  17. uni.setStorageSync(key + postfix, timestamp + "")
  18. } else {
  19. uni.removeStorageSync(key + postfix)
  20. }
  21. }
  22. /**
  23. * 从本地缓存中同步获取指定 key 对应的内容。
  24. * @param {String} key 本地缓存中的指定的 key
  25. * @param def 获取失败时的默认内容,可以为空.
  26. */
  27. simpleCache.get = function(key, def) {
  28. var deadtime = parseInt(uni.getStorageSync(key + postfix))
  29. if (deadtime) {
  30. if (parseInt(deadtime) < Date.parse(new Date()) / 1000) {
  31. //已过期
  32. if (def) {
  33. return def;
  34. } else {
  35. //清除过期时间
  36. uni.removeStorageSync(key + postfix)
  37. //移除缓存
  38. uni.removeStorageSync(key)
  39. return false;
  40. }
  41. }
  42. }
  43. var res = uni.getStorageSync(key);
  44. if (res) {
  45. return res;
  46. } else {
  47. if (def == undefined || def == "") {
  48. def = false;
  49. uni.removeStorageSync(key)
  50. }
  51. return def;
  52. }
  53. }
  54. /**
  55. * 从本地缓存中同步移除指定 key。
  56. * @param {String} key 本地缓存中的指定的 key
  57. */
  58. simpleCache.remove = function(key) {
  59. uni.removeStorageSync(key);
  60. uni.removeStorageSync(key + postfix);
  61. }
  62. /**
  63. * 同步清理本地数据缓存。
  64. */
  65. simpleCache.clear = function() {
  66. // 这里面其实可以扩展你不想清理的缓存,比如你保存的用户登录状态. 在清理之前先获取一次.
  67. // var user = simpleCache.get("user_info");
  68. uni.clearStorageSync();
  69. // simpleCache.put("user_info",user); // 等 其它的自行扩展.
  70. }
  71. simpleCache.image_cache=function(id_key,image_url,isError,time=3*24*60*60) {
  72. let imgTemp= simpleCache.get(id_key)
  73. if(!imgTemp){
  74. //本地没有缓存,需要下载
  75. uni.downloadFile({
  76. url: image_url,
  77. success: (res) => {
  78. if (res.statusCode === 200) {
  79. let temp=res.tempFilePath
  80. simpleCache.put(id_key,temp,time)
  81. }
  82. }
  83. });
  84. console.log("我来自网络")
  85. return image_url
  86. }else{
  87. if(isError){
  88. console.log("我发生错误了")
  89. return imgTemp
  90. }else{
  91. console.log("我没有发生错误")
  92. return image_url
  93. }
  94. }
  95. }
  96. // export default simpleCache
  97. module.exports = {
  98. put:simpleCache.put,
  99. get:simpleCache.get,
  100. remove:simpleCache.remove,
  101. clear:simpleCache.clear,
  102. cacheImg:simpleCache.image_cache
  103. }