Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import {
- BaseQueryFn,
- FetchArgs,
- FetchBaseQueryError,
- FetchBaseQueryMeta,
- QueryReturnValue,
- } from '@reduxjs/toolkit/query/react';
- import { REFRESH_SUCCESS } from 'ducks/types';
- import { getToken } from 'ducks/Auth/selectors';
- import baseQuery from './baseQuery';
- // Create a type alias for the result of baseQuery.
- type BaseQueryResult = QueryReturnValue<unknown, FetchBaseQueryError, FetchBaseQueryMeta>;
- const baseQueryWithReauth: BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError> = (
- args,
- api,
- extraOptions,
- ) => Promise.resolve(baseQuery(args, api, extraOptions)).then((result: BaseQueryResult) => {
- if (result.error?.status === 401) {
- const state = api.getState();
- const token = getToken(state);
- if (token?.RefreshToken) {
- // Attempt to refresh the token.
- return Promise.resolve(
- baseQuery(
- {
- url: '/refresh',
- method: 'GET',
- headers: {
- Authorization: `Bearer ${token.RefreshToken}`,
- },
- },
- api,
- extraOptions,
- ),
- ).then((refreshResult: BaseQueryResult) => {
- if (refreshResult.data) {
- // Dispatch the token refresh success action.
- api.dispatch({ type: REFRESH_SUCCESS, payload: refreshResult.data });
- // Retry the original request and return its promise.
- return baseQuery(args, api, extraOptions);
- }
- // If token refresh fails, log out the user.
- api.dispatch({ type: 'auth/logout' });
- return result;
- });
- }
- }
- return result;
- });
- export default baseQueryWithReauth;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement