storage.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. 'use strict';
  2. const {
  3. Validator
  4. } = require('./validator.js')
  5. const {
  6. CacheKeyCascade
  7. } = require('./uni-cloud-cache.js')
  8. class Storage {
  9. constructor(type, keys) {
  10. this._type = type || null
  11. this._keys = keys || []
  12. }
  13. async get(key, fallback) {
  14. this.validateKey(key)
  15. const result = await this.create(key, fallback).get()
  16. return result.value
  17. }
  18. async set(key, value, expiresIn) {
  19. this.validateKey(key)
  20. this.validateValue(value)
  21. const expires_in = this.getExpiresIn(expiresIn)
  22. if (expires_in !== 0) {
  23. await this.create(key).set(this.getValue(value), expires_in)
  24. }
  25. }
  26. async remove(key) {
  27. this.validateKey(key)
  28. await this.create(key).remove()
  29. }
  30. async ttl(key) {
  31. this.validateKey(key)
  32. // 后续考虑支持
  33. }
  34. getKeyString(key) {
  35. const keyArray = [Storage.Prefix]
  36. this._keys.forEach((name) => {
  37. keyArray.push(key[name])
  38. })
  39. keyArray.push(this._type)
  40. return keyArray.join(':')
  41. }
  42. getValue(value) {
  43. return value
  44. }
  45. getExpiresIn(value) {
  46. if (value !== undefined) {
  47. return value
  48. }
  49. return -1
  50. }
  51. validateKey(key) {
  52. Validator.Key(this._keys, key)
  53. }
  54. validateValue(value) {
  55. Validator.Value(value)
  56. }
  57. create(key, fallback) {
  58. const keyString = this.getKeyString(key)
  59. const options = {
  60. layers: [{
  61. type: 'database',
  62. key: keyString
  63. }, {
  64. type: 'redis',
  65. key: keyString
  66. }]
  67. }
  68. if (fallback !== null) {
  69. const fallbackFunction = fallback || this.fallback
  70. if (fallbackFunction) {
  71. options.fallback = async () => {
  72. return await fallbackFunction(key)
  73. }
  74. }
  75. }
  76. return new CacheKeyCascade(options)
  77. }
  78. }
  79. Storage.Prefix = "uni-id"
  80. const Factory = {
  81. async Get(T, key, fallback) {
  82. return await Factory.MakeUnique(T).get(key, fallback)
  83. },
  84. async Set(T, key, value, expiresIn) {
  85. await Factory.MakeUnique(T).set(key, value, expiresIn)
  86. },
  87. async Remove(T, key) {
  88. await Factory.MakeUnique(T).remove(key)
  89. },
  90. MakeUnique(T) {
  91. return new T()
  92. }
  93. }
  94. module.exports = {
  95. Storage,
  96. Factory
  97. };