summaryrefslogtreecommitdiff
path: root/packages/idb-bridge/src/util/canInjectKey.ts
blob: c6c9c24ab4a7ffabce79393400a330b97123f5ab (plain)
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
import { KeyPath, Value } from "./types";

// http://w3c.github.io/IndexedDB/#check-that-a-key-could-be-injected-into-a-value
const canInjectKey = (keyPath: KeyPath, value: Value) => {
  if (Array.isArray(keyPath)) {
    // tslint:disable-next-line max-line-length
    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 identifiers = keyPath.split(".");
  if (identifiers.length === 0) {
    throw new Error("Assert: identifiers is not empty");
  }
  identifiers.pop();

  for (const identifier of identifiers) {
    if (typeof value !== "object" && !Array.isArray(value)) {
      return false;
    }

    const hop = value.hasOwnProperty(identifier);
    if (!hop) {
      return true;
    }

    value = value[identifier];
  }

  return typeof value === "object" || Array.isArray(value);
};

export default canInjectKey;