-
-
Notifications
You must be signed in to change notification settings - Fork 737
/
Copy pathsecret.js
51 lines (43 loc) · 1.03 KB
/
secret.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
const { deepClone } = require('./utils');
const maskedString = '*****';
/** @param {string} secret */
class Secret {
constructor(secret) {
this._secret = secret;
}
/** @returns {string} */
toString() {
return this._secret;
}
getMasked() {
return maskedString;
}
/**
* @param {...*} secret
* @returns {Secret}
*/
static secret(secret) {
if (typeof secret === 'object') {
const fields = Array.from(arguments);
fields.shift();
return secretObject(secret, fields);
}
return new Secret(secret);
}
}
function secretObject(obj, fieldsToHide = []) {
const handler = {
get(obj, prop) {
if (prop === 'toString') {
return function () {
const maskedObject = deepClone(obj);
fieldsToHide.forEach(f => (maskedObject[f] = maskedString));
return JSON.stringify(maskedObject);
};
}
return fieldsToHide.includes(prop) ? new Secret(obj[prop]) : obj[prop];
},
};
return new Proxy(obj, handler);
}
module.exports = Secret;