Files
emaui/apps/portal/src/app/store/index.ts

59 lines
1.4 KiB
TypeScript

import { configureStore } from "@reduxjs/toolkit";
import { baseApi, configureTokenRefresh } from "@ema-platform/api";
import {
authReducer,
signupReducer,
configureAuthStorage,
authStorage,
refreshAccessToken,
logout,
setToken,
} from "@ema-platform/auth";
import type { AuthUser, CurrentProfile } from "@ema-platform/auth";
configureAuthStorage("ema-portal", true);
const preloadedAuth = (() => {
const token = authStorage.getToken();
const user = authStorage.getUser<AuthUser>();
const profile = authStorage.getProfile<CurrentProfile>();
if (token && user) {
return {
token,
user,
isAuthenticated: true,
currentProfile: profile ?? null,
};
}
return undefined;
})();
export const store = configureStore({
reducer: {
auth: authReducer,
signup: signupReducer,
[baseApi.reducerPath]: baseApi.reducer,
},
preloadedState: preloadedAuth ? { auth: preloadedAuth } : undefined,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(baseApi.middleware),
});
configureTokenRefresh({
onTokenExpired: async () => {
const token = await refreshAccessToken();
store.dispatch(setToken(token));
return token;
},
onAuthFailure: () => {
store.dispatch(logout());
window.location.href = "/";
},
});
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;