memory.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /* eslint-disable */
  2. export interface Cache<V = any> {
  3. value?: V
  4. timeoutId?: ReturnType<typeof setTimeout>
  5. time?: number
  6. alive?: number
  7. }
  8. const NOT_ALIVE = 0
  9. export class Memory<T = any, V = any> {
  10. private cache: { [key in keyof T]?: Cache<V> } = {}
  11. private alive: number
  12. constructor(alive = NOT_ALIVE) {
  13. // 30天有效
  14. this.alive = alive * 1000 * 30
  15. }
  16. get getCache() {
  17. return this.cache
  18. }
  19. setCache(cache) {
  20. this.cache = cache
  21. }
  22. get<K extends keyof T>(key: K) {
  23. return this.cache[key]
  24. }
  25. set<K extends keyof T>(key: K, value: V, expires?: number) {
  26. let item = this.get(key)
  27. if (!expires || (expires as number) <= 0) {
  28. expires = this.alive
  29. }
  30. if (item) {
  31. if (item.timeoutId) {
  32. clearTimeout(item.timeoutId)
  33. item.timeoutId = undefined
  34. }
  35. item.value = value
  36. } else {
  37. item = { value, alive: expires }
  38. this.cache[key] = item
  39. }
  40. if (!expires) {
  41. return value
  42. }
  43. const now = new Date().getTime()
  44. item.time = now + this.alive
  45. item.timeoutId = setTimeout(
  46. () => {
  47. this.remove(key)
  48. },
  49. expires > now ? expires - now : expires
  50. )
  51. return value
  52. }
  53. remove<K extends keyof T>(key: K) {
  54. const item = this.get(key)
  55. Reflect.deleteProperty(this.cache, key)
  56. if (item) {
  57. clearTimeout(item.timeoutId)
  58. return item.value
  59. }
  60. }
  61. resetCache(cache: { [K in keyof T]: cache }) {
  62. Object.keys(cache).forEach(key => {
  63. const k = key as any as keyof T
  64. const item = cache[k]
  65. if (item && item.time) {
  66. const now = new Date().getTime()
  67. const expire = item.time
  68. if (expire > now) {
  69. this.set(k, item.value, expire)
  70. }
  71. }
  72. })
  73. }
  74. clear() {
  75. Object.keys(this.cache).forEach(key => {
  76. const item = this.cache[key]
  77. item.timeoutId && clearTimeout(item.timeoutId)
  78. })
  79. this.cache = {}
  80. }
  81. }