Advertisement
minafaw3

baseQueryWithReauth

Feb 12th, 2025
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. import {
  2. BaseQueryFn,
  3. FetchArgs,
  4. FetchBaseQueryError,
  5. FetchBaseQueryMeta,
  6. QueryReturnValue,
  7. } from '@reduxjs/toolkit/query/react';
  8. import { REFRESH_SUCCESS } from 'ducks/types';
  9. import { getToken } from 'ducks/Auth/selectors';
  10. import baseQuery from './baseQuery';
  11.  
  12. // Create a type alias for the result of baseQuery.
  13. type BaseQueryResult = QueryReturnValue<unknown, FetchBaseQueryError, FetchBaseQueryMeta>;
  14.  
  15. const baseQueryWithReauth: BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError> = (
  16. args,
  17. api,
  18. extraOptions,
  19. ) => Promise.resolve(baseQuery(args, api, extraOptions)).then((result: BaseQueryResult) => {
  20. if (result.error?.status === 401) {
  21. const state = api.getState();
  22. const token = getToken(state);
  23.  
  24. if (token?.RefreshToken) {
  25. // Attempt to refresh the token.
  26. return Promise.resolve(
  27. baseQuery(
  28. {
  29. url: '/refresh',
  30. method: 'GET',
  31. headers: {
  32. Authorization: `Bearer ${token.RefreshToken}`,
  33. },
  34. },
  35. api,
  36. extraOptions,
  37. ),
  38. ).then((refreshResult: BaseQueryResult) => {
  39. if (refreshResult.data) {
  40. // Dispatch the token refresh success action.
  41. api.dispatch({ type: REFRESH_SUCCESS, payload: refreshResult.data });
  42. // Retry the original request and return its promise.
  43. return baseQuery(args, api, extraOptions);
  44. }
  45. // If token refresh fails, log out the user.
  46. api.dispatch({ type: 'auth/logout' });
  47. return result;
  48. });
  49. }
  50. }
  51. return result;
  52. });
  53. export default baseQueryWithReauth;
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement