-
Notifications
You must be signed in to change notification settings - Fork 134
/
key-map.ts
69 lines (59 loc) · 1.67 KB
/
key-map.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
66
67
68
69
import { deepGet, deepSet, firstResult, Dict } from '@orbit/utils';
import { Record, UninitializedRecord } from './record';
/**
* Maintains a map between records' ids and keys.
*/
export class KeyMap {
private _idsToKeys!: Dict<Dict<string>>;
private _keysToIds!: Dict<Dict<string>>;
constructor() {
this.reset();
}
/**
* Resets the contents of the key map.
*/
reset(): void {
this._idsToKeys = {};
this._keysToIds = {};
}
/**
* Return a key value given a model type, key name, and id.
*/
idToKey(type: string, keyName: string, idValue: string): string {
return deepGet(this._idsToKeys, [type, keyName, idValue]);
}
/**
* Return an id value given a model type, key name, and key value.
*/
keyToId(type: string, keyName: string, keyValue: string): string {
return deepGet(this._keysToIds, [type, keyName, keyValue]);
}
/**
* Store the id and key values of a record in this key map.
*/
pushRecord(record: Record | UninitializedRecord): void {
const { type, id, keys } = record;
if (!keys || !id) {
return;
}
Object.keys(keys).forEach((keyName) => {
let keyValue = keys[keyName];
if (keyValue) {
deepSet(this._idsToKeys, [type, keyName, id], keyValue);
deepSet(this._keysToIds, [type, keyName, keyValue], id);
}
});
}
/**
* Given a record, find the cached id if it exists.
*/
idFromKeys(type: string, keys: Dict<string>): string {
let keyNames = Object.keys(keys);
return firstResult(keyNames, (keyName) => {
let keyValue = keys[keyName];
if (keyValue) {
return this.keyToId(type, keyName, keyValue);
}
});
}
}