Safe property access for JavaScript objects using Proxy Object.
Proxy Object (Latest Chrome and Firefox support it!)
import SafeObject from 'safe-object-proxy';
const so = SafeObject({
foo: 'hello',
bar: {
baz: true
},
test: [0, 1, 2]
});
so.foo(); // 'hello'
so.bar.baz(); // true
so.test[1](); // 1
so.throws.no.error.property.not.exists(); // undefined
so.bar.baz = false; // You can update properties
so.bar.bar.bar = 'Not updated'; // Do nothing if you try to update the property not exists
// pattern match whether the property is exist or not
so.foo(
(val) => val + ' world',
() => 'Nothing'
); // 'hello world'
so.foofoo(
(val) => 'This is never called',
() => 'Nothing'
); // 'Nothing'
It will be useful to use for untrusted data like the response data of an Ajax request.
fetch('/api/somthing')
.then(res => res.json)
.then(json => SafeObject(json))
.then(data => {
console.log(data.user.media.uploadedImages[0]());
});
MIT