-
Notifications
You must be signed in to change notification settings - Fork 72
/
client.js
executable file
·114 lines (76 loc) · 2.85 KB
/
client.js
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
112
113
114
'use strict';
const Hoek = require('@hapi/hoek');
const Boom = require('@hapi/boom');
const internals = {
validate: Symbol('validate')
};
internals.defaults = {
partition: 'catbox'
};
module.exports = class {
constructor(engine, options) {
Hoek.assert(engine, 'Missing catbox client engine');
Hoek.assert(typeof engine === 'object' || typeof engine === 'function', 'engine must be an engine object or engine prototype (function)');
Hoek.assert(typeof engine === 'function' || !options, 'Can only specify options with function engine config');
const settings = Object.assign({}, internals.defaults, options);
Hoek.assert(settings.partition.match(/^[\w\-]+$/), 'Invalid partition name:' + settings.partition);
this.connection = (typeof engine === 'object' ? engine : new engine(settings));
}
async start() {
await this.connection.start();
}
async stop() {
await this.connection.stop();
}
isReady() {
return this.connection.isReady();
}
validateSegmentName(name) {
return this.connection.validateSegmentName(name);
}
async get(key) {
this[internals.validate](key, null);
if (key === null) {
return null;
}
const result = await this.connection.get(key);
if (!result ||
result.item === undefined ||
result.item === null) {
return null; // Not found
}
const now = Date.now();
const expires = result.stored + result.ttl;
const ttl = expires - now;
if (ttl <= 0) {
return null; // Expired
}
const cached = {
item: result.item,
stored: result.stored,
ttl
};
return cached; // Valid
}
async set(key, value, ttl) {
this[internals.validate](key);
if (ttl <= 0) {
return; // Not cachable (or bad rules)
}
await this.connection.set(key, value, ttl);
}
async drop(key) {
this[internals.validate](key);
await this.connection.drop(key); // Always drop, regardless of caching rules
}
[internals.validate](key, allow = {}) {
if (!this.isReady()) {
throw Boom.internal('Disconnected'); // Disconnected
}
const isValidKey = (key && typeof key.id === 'string' &&
key.segment && typeof key.segment === 'string');
if (!isValidKey && key !== allow) {
throw Boom.internal('Invalid key');
}
}
};