Skip to content

Instantly share code, notes, and snippets.

@kitten
Last active August 17, 2022 09:35
Show Gist options
  • Save kitten/6050e4f447cb29724546dd2e0e68b470 to your computer and use it in GitHub Desktop.
Save kitten/6050e4f447cb29724546dd2e0e68b470 to your computer and use it in GitHub Desktop.
import { pipe, share, filter, map, mergeMap, fromPromise, fromValue } from 'wonka';
const addTokenToOperation = (operation, token) => {
const fetchOptions = typeof operation.context.fetchOptions === 'function'
? operation.context.fetchOptions()
: (operation.context.fetchOptions || {});
return {
...operation,
context: {
...operation.context,
fetchOptions: {
...fetchOptions,
headers: {
...fetchOptions.headers,
Authorization: `Bearer ${token}`
},
}
}
};
};
/**
This exchange performs authentication and is a recipe.
The `getToken` function gets a token, e.g. from local storage.
The `isTokenExpired` function checks whether we need to refresh.
The `refreshToken` function calls fetch to get a new token and stores it in local storage.
*/
const authExchange = () => ({ forward }) => {
let refreshTokenPromise = null;
return ops$ => {
// We share the operations stream
const sharedOps$ = pipe(ops$, share);
const withToken$ = pipe(
sharedOps$,
// Filter by non-teardowns
filter(operation => operation.operationName !== 'teardown'),
mergeMap(operation => {
// check whether the token is expired
const isExpired = refreshTokenPromise || isTokenExpired();
// If it's not expired then just add it to the operation immediately
if (!isExpired) {
return fromValue(addTokenToOperation(operation, getToken()))
}
// If it's expired and we aren't refreshing it yet, start refreshing it
if (isExpired && !refreshTokenPromise) {
refreshTokenPromise = refreshToken(); // we share the promise
}
return pipe(
fromPromise(refreshTokenPromise),
map(token => {
refreshTokenPromise = null; // reset the promise variable
return addTokenToOperation(operation, token);
})
);
})
);
// We don't need to do anything for teardown operations
const withoutToken$ = pipe(
sharedOps$,
filter(operation => operation.operationName === 'teardown'),
);
return pipe(
merge([withToken$, withoutToken$]),
forward
);
};
};
import { pipe, share, filter, map, mergeMap, fromPromise, fromValue, takeUntil } from 'wonka';
const addTokenToOperation = (operation, token) => {
const fetchOptions = typeof operation.context.fetchOptions === 'function'
? operation.context.fetchOptions()
: (operation.context.fetchOptions || {});
return {
...operation,
context: {
...operation.context,
fetchOptions: {
...fetchOptions,
headers: {
...fetchOptions.headers,
Authorization: `Bearer ${token}`
},
}
}
};
};
/**
This exchange performs authentication and is a recipe.
The `getToken` function gets a token, e.g. from local storage.
The `isTokenExpired` function checks whether we need to refresh.
The `refreshToken` function calls fetch to get a new token and stores it in local storage.
*/
const authExchange = () => ({ forward }) => {
let refreshTokenPromise = null;
return ops$ => {
// We share the operations stream
const sharedOps$ = pipe(ops$, share);
const withToken$ = pipe(
sharedOps$,
// Filter by non-teardowns
filter(operation => operation.operationName !== 'teardown'),
mergeMap(operation => {
// check whether the token is expired
const isExpired = refreshTokenPromise || isTokenExpired();
// If it's not expired then just add it to the operation immediately
if (!isExpired) {
return fromValue(addTokenToOperation(operation, getToken()))
}
// If it's expired and we aren't refreshing it yet, start refreshing it
if (isExpired && !refreshTokenPromise) {
refreshTokenPromise = refreshToken(); // we share the promise
}
const { key } = operation;
// Listen for cancellation events for this operation
const teardown$ = pipe(
sharedOps$,
filter(op => op.operationName === 'teardown' && op.key === key)
);
return pipe(
fromPromise(refreshTokenPromise),
// Don't bother to forward the operation, if it has been cancelled
// while we were refreshing
takeUntil(teardown$),
map(token => {
refreshTokenPromise = null; // reset the promise variable
return addTokenToOperation(operation, token);
})
);
})
);
// We don't need to do anything for teardown operations
const withoutToken$ = pipe(
sharedOps$,
filter(operation => operation.operationName === 'teardown'),
);
return pipe(
merge([withToken$, withoutToken$]),
forward
);
};
};
import { pipe, share, filter, map, mergeMap, fromPromise, fromValue, takeUntil, onPush } from 'wonka';
const addTokenToOperation = (operation, token) => {
const fetchOptions = typeof operation.context.fetchOptions === 'function'
? operation.context.fetchOptions()
: (operation.context.fetchOptions || {});
return {
...operation,
context: {
...operation.context,
fetchOptions: {
...fetchOptions,
headers: {
...fetchOptions.headers,
Authorization: `Bearer ${token}`
},
}
}
};
};
/**
This exchange performs authentication and is a recipe.
The `getToken` function gets a token, e.g. from local storage.
The `isTokenExpired` function checks whether we need to refresh.
The `refreshToken` function calls fetch to get a new token and stores it in local storage.
*/
const authExchange = () => ({ forward }) => {
let refreshTokenPromise = null;
return ops$ => {
// We share the operations stream
const sharedOps$ = pipe(ops$, share);
const withToken$ = pipe(
sharedOps$,
// Filter by non-teardowns
filter(operation => operation.operationName !== 'teardown'),
mergeMap(operation => {
// check whether the token is expired
const isExpired = refreshTokenPromise || isTokenExpired();
// If it's not expired then just add it to the operation immediately
if (!isExpired) {
return fromValue(addTokenToOperation(operation, getToken()))
}
// If it's expired and we aren't refreshing it yet, start refreshing it
if (isExpired && !refreshTokenPromise) {
refreshTokenPromise = refreshToken(); // we share the promise
}
const { key } = operation;
// Listen for cancellation events for this operation
const teardown$ = pipe(
sharedOps$,
filter(op => op.operationName === 'teardown' && op.key === key)
);
return pipe(
fromPromise(refreshTokenPromise),
// Don't bother to forward the operation, if it has been cancelled
// while we were refreshing
takeUntil(teardown$),
map(token => {
refreshTokenPromise = null; // reset the promise variable
return addTokenToOperation(operation, token);
})
);
})
);
// We don't need to do anything for teardown operations
const withoutToken$ = pipe(
sharedOps$,
filter(operation => operation.operationName === 'teardown'),
);
return pipe(
merge([withToken$, withoutToken$]),
forward,
onPush(result => {
if (result.error && result.error.networkError /* TODO: also add a check for 401 Unauthorized here! */) {
invalidateToken(); // here you'd invalidate your local token synchronously
// this is so our pretend `isTokenExpired()` function returns `true` next time around
}
})
);
};
};
// Then you can combine this with the retryExchange
import { retryExchange } from '@urql/exchange-retry';
createClient({
exchanges: [
dedupExchange,
cacheExchange,
retryExchange({ /* optional options */ }),
authExchange(),
fetchExchange,
]
})

MIT License

Copyright (c) 2020 Formidable

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment