Skip to content

Instantly share code, notes, and snippets.

@mrsufgi
Created November 26, 2018 09:26
Show Gist options
  • Save mrsufgi/842b1dafed63745e14e2876e41f5eeb4 to your computer and use it in GitHub Desktop.
Save mrsufgi/842b1dafed63745e14e2876e41f5eeb4 to your computer and use it in GitHub Desktop.
proxy implementation example
/*
Hey All! Most devs (including me) uses Proxy and Decorators on a daily basis but doesn't know to implement or use one. I wanted to show two snippets me and @Nicolas Mendzylewski wrote that might be useful in the future:
const withOBAPIAuth = function withOBAPIAuthenticationToken(proto) {
const handler = {
get(target, propKey) {
const method = target[propKey];
const { token } = proto;
if (typeof method === 'function' && method !== proto) {
return async (...args) => {
let result;
try {
result = await method.apply(proto, args);
} catch (error) {
console.error('failed fetching data from remote service', { error });
if (error.statusCode === 401) {
proto.token = await getToken();
result = await method.apply(proto, args);
}
}
return result;
};
}
return method;
},
};
return new Proxy(proto, handler);
}; */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment