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