MinCache.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. let cacheMap = new Map()
  2. let timeoutDefault = 1200
  3. function isTimeout (name) {
  4. const data = cacheMap.get(name)
  5. if (!data) return true
  6. if (data.timeout === 0) return false
  7. const currentTime = Date.now()
  8. const overTime = (currentTime - data.createTime) / 1000
  9. if (overTime > data.timeout) {
  10. cacheMap.delete(name)
  11. if (name.startsWith('_')) {
  12. try {
  13. uni.removeStorageSync(name)
  14. } catch (e) {
  15. console.log(e)
  16. }
  17. }
  18. return true
  19. }
  20. return false
  21. }
  22. class CacheCell {
  23. constructor (data, timeout) {
  24. this.data = data
  25. this.timeout = timeout
  26. this.createTime = Date.now()
  27. }
  28. }
  29. class MinCache {
  30. constructor (timeout) {
  31. try {
  32. const res = uni.getStorageInfoSync()
  33. res.keys.forEach(name => {
  34. try {
  35. const value = uni.getStorageSync(name)
  36. cacheMap.set(name, value)
  37. } catch (e) {
  38. console.log(e)
  39. }
  40. })
  41. } catch (e) {
  42. console.log(e)
  43. }
  44. timeoutDefault = timeout
  45. }
  46. set (name, data, timeout = timeoutDefault) {
  47. const cachecell = new CacheCell(data, timeout)
  48. let cache = null
  49. if (name.startsWith('_')) {
  50. try {
  51. uni.setStorageSync(name, cachecell)
  52. cache = cacheMap.set(name, cachecell)
  53. } catch (e) {
  54. console.log(e)
  55. }
  56. } else {
  57. cache = cacheMap.set(name, cachecell)
  58. }
  59. return cache
  60. }
  61. get (name) {
  62. return isTimeout(name) ? null : cacheMap.get(name).data
  63. }
  64. delete (name) {
  65. let value = false
  66. if (name.startsWith('_')) {
  67. try {
  68. uni.removeStorageSync(name)
  69. value = cacheMap.delete(name)
  70. } catch (e) {
  71. console.log(e)
  72. }
  73. } else {
  74. value = cacheMap.delete(name)
  75. }
  76. return value
  77. }
  78. has (name) {
  79. return !isTimeout(name)
  80. }
  81. clear () {
  82. let value = false
  83. try {
  84. uni.clearStorageSync()
  85. cacheMap.clear()
  86. value = true
  87. } catch (e) {
  88. console.log(e)
  89. }
  90. return value
  91. }
  92. }
  93. MinCache.install = function (Vue, {timeout = 1200} = {}) {
  94. Vue.prototype.$cache = new MinCache(timeout)
  95. }
  96. export default MinCache