Skip to content

Commit

Permalink
fix: secret function
Browse files Browse the repository at this point in the history
  • Loading branch information
kobenguyent committed Jun 22, 2023
1 parent 06045e1 commit 581241b
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 15 deletions.
18 changes: 3 additions & 15 deletions lib/secret.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,21 +31,9 @@ class Secret {
}

function secretObject(obj, fieldsToHide = []) {
const handler = {
get(obj, prop) {
if (prop === 'toString') {
return function () {
const maskedObject = deepClone(obj);
fieldsToHide.forEach(f => maskedObject[f] = '****');
return JSON.stringify(maskedObject);
};
}

return obj[prop];
},
};

return new Proxy(obj, handler);
const maskedObject = deepClone(obj);
fieldsToHide.forEach(f => maskedObject[f] = new Secret(maskedObject[f]));
return maskedObject;
}

module.exports = Secret;
19 changes: 19 additions & 0 deletions test/unit/secret_test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const expect = require('expect');
const Secret = require('../../lib/secret');

describe('Secret tests', () => {
it('should be the Secret instance', () => {
const string = Secret.secret('hello');
expect(string).toBeInstanceOf(Secret);
});

it('should be the Secret instance when using as object', () => {
const obj = Secret.secret({ password: 'world' }, 'password');
expect(obj.password).toBeInstanceOf(Secret);
});

it('should mask the field when provided', () => {
const obj = Secret.secret({ password: 'world' }, 'password');
expect(obj.password.getMasked()).toBe('*****');
});
});

0 comments on commit 581241b

Please sign in to comment.