Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/util/key-value-store.ts
1447 views
1
/*
2
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
/*
7
Very, very simple key:value store.
8
9
The keys can be arbitrary json-able objects.
10
A frozen copy of the object is saved in the key:value store,
11
so it won't get mutated.
12
*/
13
14
import json0 from "json-stable-stringify";
15
16
function json(x) {
17
return json0(x) ?? "";
18
}
19
20
export const key_value_store = () => new KeyValueStore();
21
22
class KeyValueStore {
23
private _data?: object;
24
25
constructor() {
26
this.set = this.set.bind(this);
27
this.get = this.get.bind(this);
28
this.delete = this.delete.bind(this);
29
this.close = this.close.bind(this);
30
this._data = {};
31
}
32
33
assert_not_closed() {
34
if (this._data == null) {
35
throw Error("closed -- KeyValueStore");
36
}
37
}
38
39
set(key, value) {
40
this.assert_not_closed();
41
if (value.freeze != null) {
42
// supported by modern browsers
43
value = value.freeze(); // so doesn't get mutated
44
}
45
if (this._data) this._data[json(key)!] = value;
46
}
47
48
get(key) {
49
this.assert_not_closed();
50
return this._data?.[json(key)!];
51
}
52
53
delete(key) {
54
this.assert_not_closed();
55
delete this._data?.[json(key)!];
56
}
57
58
close() {
59
delete this._data;
60
}
61
}
62
63