This commit is contained in:
2024-04-09 14:15:41 +03:00
parent f032751aa2
commit afbb1253ee
6 changed files with 67 additions and 11 deletions

View File

@ -1,13 +1,35 @@
import { configureStore, createAction, createReducer } from "@reduxjs/toolkit";
import { setupListeners } from "@reduxjs/toolkit/query";
import { AuthApi } from "../slice/AuthApi";
import { AuthApi, User } from "../slice/AuthApi";
export type authState = {
token: string | null;
user: { name: string | null; username: string } | null;
};
const initialAuthState: authState = {
token: null,
user: null,
};
export const updateToken = createAction<string>("auth/updateToken");
export const getLocalToken = createAction("auth/getLocalToken");
export const updateUser = createAction<User>("auth/updateUser");
const parseJwt = (token: string): { sub: string; exp: number } => {
const base64Url = token.split(".")[1];
const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
const jsonPayload = decodeURIComponent(
window
.atob(base64)
.split("")
.map(function (c) {
return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
})
.join("")
);
return JSON.parse(jsonPayload);
};
export const store = configureStore({
@ -15,12 +37,19 @@ export const store = configureStore({
// Add the generated reducer as a specific top-level slice
[AuthApi.reducerPath]: AuthApi.reducer,
auth: createReducer(initialAuthState, (builder) => {
builder.addCase(createAction("auth/token"), (state, _) => {
builder.addCase(updateToken, (state, action) => {
state.token = action.payload;
localStorage.setItem("token", action.payload);
});
builder.addCase(getLocalToken, (state) => {
const token: string | null = localStorage.getItem("token");
if (token) {
state.token = token;
}
});
builder.addCase(updateUser, (state, action) => {
state.user = action.payload;
});
}),
},
// Adding the api middleware enables caching, invalidation, polling,