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='65465489132';
const payload={X:1,Y:2...};
Module.updateResource({id,payload});
Module.fetchResource({id});

Comments