summaryrefslogtreecommitdiff
path: root/packages/idb-bridge/src/util/makeStoreKeyValue.ts
diff options
context:
space:
mode:
authorFlorian Dold <florian@dold.me>2021-02-24 17:33:07 +0100
committerFlorian Dold <florian@dold.me>2021-02-24 17:33:07 +0100
commit564e4f8710388ab2ae40c959c497f2e0260199ed (patch)
tree1d9f1b835bf6580977158f5eee133f8fa39f67d4 /packages/idb-bridge/src/util/makeStoreKeyValue.ts
parentbc7956c2ba685e459c94204ca30f85eef881d0ac (diff)
downloadwallet-core-564e4f8710388ab2ae40c959c497f2e0260199ed.tar.gz
wallet-core-564e4f8710388ab2ae40c959c497f2e0260199ed.tar.bz2
wallet-core-564e4f8710388ab2ae40c959c497f2e0260199ed.zip
idb: encapsulate non-JSON data correctly
Diffstat (limited to 'packages/idb-bridge/src/util/makeStoreKeyValue.ts')
-rw-r--r--packages/idb-bridge/src/util/makeStoreKeyValue.ts50
1 files changed, 49 insertions, 1 deletions
diff --git a/packages/idb-bridge/src/util/makeStoreKeyValue.ts b/packages/idb-bridge/src/util/makeStoreKeyValue.ts
index 442a69ff5..243e46e04 100644
--- a/packages/idb-bridge/src/util/makeStoreKeyValue.ts
+++ b/packages/idb-bridge/src/util/makeStoreKeyValue.ts
@@ -18,7 +18,6 @@ import { extractKey } from "./extractKey";
import { DataError } from "./errors";
import { valueToKey } from "./valueToKey";
import { structuredClone } from "./structuredClone";
-import { injectKey } from "./injectKey";
import { IDBKeyPath, IDBValidKey } from "../idbtypes";
export interface StoreKeyResult {
@@ -27,6 +26,55 @@ export interface StoreKeyResult {
value: any;
}
+export function injectKey(
+ keyPath: IDBKeyPath | IDBKeyPath[],
+ value: any,
+ key: IDBValidKey,
+): any {
+ if (Array.isArray(keyPath)) {
+ throw new Error(
+ "The key paths used in this section are always strings and never sequences, since it is not possible to create a object store which has a key generator and also has a key path that is a sequence.",
+ );
+ }
+
+ const newValue = structuredClone(value);
+
+ // Position inside the new value where we'll place the key eventually.
+ let ptr = newValue;
+
+ const identifiers = keyPath.split(".");
+ if (identifiers.length === 0) {
+ throw new Error("Assert: identifiers is not empty");
+ }
+
+ const lastIdentifier = identifiers.pop();
+
+ if (lastIdentifier === null || lastIdentifier === undefined) {
+ throw Error();
+ }
+
+ for (const identifier of identifiers) {
+ if (typeof ptr !== "object" && !Array.isArray(ptr)) {
+ throw new Error("can't inject key");
+ }
+
+ const hop = value.hasOwnProperty(identifier);
+ if (!hop) {
+ ptr[identifier] = {};
+ }
+
+ ptr = ptr[identifier];
+ }
+
+ if (!(typeof ptr === "object" || Array.isArray(ptr))) {
+ throw new Error("can't inject key");
+ }
+
+ ptr[lastIdentifier] = structuredClone(key);
+
+ return newValue;
+}
+
export function makeStoreKeyValue(
value: any,
key: IDBValidKey | undefined,