Skip to content

Instantly share code, notes, and snippets.

@banyudu
Created August 17, 2020 04:20
Show Gist options
  • Select an option

  • Save banyudu/95ff5cdc9eb046a2b77b647b45f80cd4 to your computer and use it in GitHub Desktop.

Select an option

Save banyudu/95ff5cdc9eb046a2b77b647b45f80cd4 to your computer and use it in GitHub Desktop.
ES6 Deep Proxy
const _ = require('lodash')
const protectCache = new Set()
const protect = (val) => {
return new Proxy(val, {
get: function (obj, prop) {
// recursive
const value = obj[prop]
if ((_.isPlainObject(value) || Array.isArray(value)) && !protectCache.has(value)) {
const result = protect(value)
protectCache.add(result)
return result
}
return obj[prop];
},
set: function (obj, prop, value) {
// your actions here
// ... ...
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
console.warn('Blocked setter in variable protecter, the blocked prop is: ', prop)
} else {
obj[prop] = value
}
// always return true if you don't want to throw in strict mode
return true
},
deleteProperty: function (obj, prop) {
// your actions here
// ... ...
// always return true if you don't want to throw in strict mode
console.warn('Blocked delete action in variable protecter, the blocked prop is: ', prop)
return true
}
})
}
// usage
const obj = protect({})
obj.hello = 1 // ok
obj.hello = 2 // blocked
obj.hello = 1 // blocked
delete obj.hello // blocked
delete obj['hello'] // blocked
obj.foo = { bar: 1 } // ok
obj.foo.bar = 2 // blocked
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment