Skip to content

Instantly share code, notes, and snippets.

@kdepp
Last active January 31, 2018 02:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kdepp/8550f017b8cc5f0abdc74ecb90ce6a98 to your computer and use it in GitHub Desktop.
Save kdepp/8550f017b8cc5f0abdc74ecb90ce6a98 to your computer and use it in GitHub Desktop.
withAccessToken
const getAccessToken = () => {
const pGetToken = db ? getAccessTokenFromDB() : Promise.resolve()
return pGetToken.then(token => {
if (token) return token
return getAccessTokenFromRemote()
.then(data => {
if (!data || !data.access_token) {
throw new Error('No access token in token api response')
}
if (!db) return data.access_token
return db.ref('paypal_access_token')
.set({
access_token: data.access_token,
expire: new Date() * 1 + data.expires_in * 1000
})
.then(() => data.access_token)
})
})
.then(token => {
console.log('Got paypal access token', token)
jwtRequest.saveToken(token)
})
.catch(e => {
console.error(e.stack)
})
}
const withAccessToken = (fn) => (...args) => {
const accessToken = jwtRequest.getToken()
const p = accessToken ? Promise.resolve()
: getAccessTokenFromRemote().then(data => {
console.log('remote access token', data.access_token)
jwtRequest.saveToken(data.access_token)
})
return p.then(() => fn(...args))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment