Skip to main content

Posts

Featured

Proxy pattern

Use case 1: Multiple functions share some parameters, and we want to avoid writing those parameters for every call. module.exports = { fetchResource : ({ token,id }) => { // ... }, updateResource: ({ token,id,payload }) => { // ... }, deleteResource: ({ token,id }) => { // ... }, fetchSomeOtherResource: ({ token,id }) => { // ... } } In the example, token is shared between all the functions. We can use a proxy to store the token, and it will pass it as a parameter to the targeted functions before being called. const handler= { shared:{}, setShared:(object={})=> this.shared={...this.shared,...object} get:(target,prop,receiver)=>{ if(this[props]) return (args)=>this[props](args) return (args)=>target[props]({...this.shared,...args}) } } const Module = new Proxy (require("PATH_TO_MODULE"),handler); Module.setShared({token:'AZERTYUIOQSDFGHJKLM'}) const id='

Latest Posts