storage.js 2.0 KB

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