Path: blob/master/src/packages/util/key-value-store.ts
1447 views
/*1* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45/*6Very, very simple key:value store.78The keys can be arbitrary json-able objects.9A frozen copy of the object is saved in the key:value store,10so it won't get mutated.11*/1213import json0 from "json-stable-stringify";1415function json(x) {16return json0(x) ?? "";17}1819export const key_value_store = () => new KeyValueStore();2021class KeyValueStore {22private _data?: object;2324constructor() {25this.set = this.set.bind(this);26this.get = this.get.bind(this);27this.delete = this.delete.bind(this);28this.close = this.close.bind(this);29this._data = {};30}3132assert_not_closed() {33if (this._data == null) {34throw Error("closed -- KeyValueStore");35}36}3738set(key, value) {39this.assert_not_closed();40if (value.freeze != null) {41// supported by modern browsers42value = value.freeze(); // so doesn't get mutated43}44if (this._data) this._data[json(key)!] = value;45}4647get(key) {48this.assert_not_closed();49return this._data?.[json(key)!];50}5152delete(key) {53this.assert_not_closed();54delete this._data?.[json(key)!];55}5657close() {58delete this._data;59}60}616263