Created
November 26, 2018 09:26
-
-
Save mrsufgi/842b1dafed63745e14e2876e41f5eeb4 to your computer and use it in GitHub Desktop.
proxy implementation example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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