江西小程序管理端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

111 lines
1.9 KiB

1 year ago
  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. getKeyString(key) {
  43. const keyArray = [Storage.Prefix]
  44. this._keys.forEach((name) => {
  45. keyArray.push(key[name])
  46. })
  47. keyArray.push(this._type)
  48. return keyArray.join(':')
  49. }
  50. getValue(value) {
  51. return value
  52. }
  53. getExpiresIn(value) {
  54. if (value !== undefined) {
  55. return value
  56. }
  57. return -1
  58. }
  59. validateKey(key) {
  60. Validator.Key(this._keys, key)
  61. }
  62. validateValue(value) {
  63. Validator.Value(value)
  64. }
  65. create(key, fallback) {
  66. const keyString = this.getKeyString(key)
  67. const options = {
  68. layers: [{
  69. type: 'database',
  70. key: keyString
  71. }, {
  72. type: 'redis',
  73. key: keyString
  74. }]
  75. }
  76. const _this = this
  77. return new CacheKeyCascade({
  78. ...options,
  79. fallback: async function() {
  80. if (fallback) {
  81. return fallback(key)
  82. } else if (_this.fallback) {
  83. return _this.fallback(key)
  84. }
  85. }
  86. })
  87. }
  88. }
  89. Storage.Prefix = "uni-id"
  90. module.exports = {
  91. Storage
  92. };