-
Notifications
You must be signed in to change notification settings - Fork 3
/
couchbase-cache.ts
65 lines (57 loc) 路 1.54 KB
/
couchbase-cache.ts
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
import {CachePlugin} from "./cache-factory";
import {Bucket, Cluster} from "couchbase";
interface CouchbaseCacheOptions {
host: string;
bucketName: string;
username?: string;
password?: string;
timeout?: number;
}
class CouchbaseCache implements CachePlugin {
private cluster!: Cluster;
private bucket!: Bucket;
private options: CouchbaseCacheOptions;
constructor(options: CouchbaseCacheOptions) {
this.options = options;
}
async connect() {
return new Promise((resolve, reject) => {
this.cluster = new Cluster(this.options.host);
if (this.options.username && this.options.password) {
this.cluster.authenticate(
this.options.username,
this.options.password,
);
}
this.bucket = this.cluster.openBucket(this.options.bucketName);
this.bucket.on('connect', resolve);
this.bucket.on('error', reject);
this.configure();
});
}
private configure() {
if (this.options.timeout) {
this.bucket.operationTimeout = this.options.timeout;
}
}
get<T>(key: string): Promise<T | null> {
return new Promise(resolve => {
this.bucket.get(key, (err, data) => {
resolve(data && data.value ? data.value : null);
});
});
}
set(key: string, value: unknown, ms?: number): Promise<void> {
return new Promise(resolve => {
this.bucket.insert(key, value, {
expiry: ms ? Math.floor(ms / 1000) : undefined
}, _ => {
resolve();
});
});
}
}
export {
CouchbaseCacheOptions,
CouchbaseCache
};