-
-
Notifications
You must be signed in to change notification settings - Fork 495
/
ComputedDataProxy.js
83 lines (72 loc) · 2.18 KB
/
ComputedDataProxy.js
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
const lodashSet = require("lodash/set");
const lodashGet = require("lodash/get");
const lodashIsPlainObject = require("lodash/isPlainObject");
class ComputedDataProxy {
constructor(computedKeys) {
if (Array.isArray(computedKeys)) {
this.computedKeys = new Set(computedKeys);
} else {
this.computedKeys = computedKeys;
}
}
isArrayOrPlainObject(data) {
return Array.isArray(data) || lodashIsPlainObject(data);
}
getProxyData(data, keyRef) {
let undefinedValue = "__11TY_UNDEFINED__";
if (this.computedKeys) {
for (let key of this.computedKeys) {
if (lodashGet(data, key, undefinedValue) === undefinedValue) {
lodashSet(data, key, "");
}
}
}
return this._getProxyData(data, keyRef);
}
_getProxyData(data, keyRef, parentKey = "") {
if (lodashIsPlainObject(data)) {
return new Proxy(
{},
{
get: (obj, key) => {
// console.log( obj, key, parentKey );
if (typeof key !== "string") {
return obj[key];
}
let newKey = `${parentKey ? `${parentKey}.` : ""}${key}`;
let newData = this._getProxyData(data[key], keyRef, newKey);
if (!this.isArrayOrPlainObject(newData)) {
keyRef.add(newKey);
}
return newData;
}
}
);
} else if (Array.isArray(data)) {
return new Proxy([], {
get: (obj, key) => {
let newKey = `${parentKey}[${key}]`;
let newData = this._getProxyData(data[key], keyRef, newKey);
if (!this.isArrayOrPlainObject(newData)) {
keyRef.add(newKey);
}
return newData;
}
});
}
// everything else!
return data;
}
async findVarsUsed(fn, data = {}) {
let keyRef = new Set();
// careful, logging proxyData will mess with test results!
let proxyData = this.getProxyData(data, keyRef);
// squelch console logs for this fake proxy data pass 😅
let savedLog = console.log;
console.log = () => {};
await fn(proxyData);
console.log = savedLog;
return Array.from(keyRef);
}
}
module.exports = ComputedDataProxy;