| import { createAsyncThunk, createSlice, type PayloadAction } from "@reduxjs/toolkit"; |
| import type { AuthState } from "../../store/types"; |
| import type { LoginRequest } from "../../api/type"; |
| import authAPI from "../../api/authApi"; |
| |
| |
| const initialState: AuthState = { |
| token: '', |
| loading: false, |
| isAuth: false, |
| error: '' |
| } |
| |
| export const loginUser = createAsyncThunk< |
| {token: string}, |
| LoginRequest, |
| { rejectValue: string } |
| >( |
| 'auth/login', |
| async (loginRequest: LoginRequest, { rejectWithValue }) => { |
| try { |
| const response = await authAPI.login(loginRequest); |
| if(response.data.code == 0) { |
| return {token: response.data.data}; |
| } |
| else |
| return rejectWithValue(response.data.message); |
| } catch { |
| return rejectWithValue('登录失败'); |
| } |
| } |
| ); |
| |
| export const refreshToken = createAsyncThunk< |
| {token: string}, |
| string, |
| { rejectValue: string } |
| >( |
| |
| 'auth/refresh', |
| async (oldToken: string, { rejectWithValue }) => { |
| try { |
| const response = await authAPI.refreshToken(oldToken); |
| if(response.data.code == 0) |
| return {token: response.data.data}; |
| else |
| return rejectWithValue(response.data.message); |
| } catch { |
| return rejectWithValue('刷新失败'); |
| } |
| } |
| ); |
| |
| const authSlice = createSlice({ |
| name: 'auth', |
| initialState, |
| reducers: { |
| logout: (state) => { |
| state.token = ''; |
| state.isAuth = false; |
| localStorage.clear() |
| }, |
| },extraReducers: (builder) => { |
| // 处理登录的异步操作 |
| builder |
| .addCase(loginUser.pending, (state) => { |
| state.loading = true; |
| }) |
| .addCase(loginUser.fulfilled, (state, action: PayloadAction<{token: string}>) => { |
| state.loading = false; |
| state.token = action.payload.token; |
| state.isAuth = true; |
| |
| localStorage.setItem('token', state.token); |
| }) |
| .addCase(loginUser.rejected, (state, action) => { |
| state.loading = false; |
| state.error = action.payload ? action.payload : '' // 错误处理 |
| }) |
| |
| // 处理刷新 token 的异步操作 |
| .addCase(refreshToken.pending, (state) => { |
| state.loading = true; |
| }) |
| .addCase(refreshToken.fulfilled, (state, action) => { |
| state.loading = false; |
| state.token = action.payload.token; |
| localStorage.setItem('token', state.token); |
| }) |
| .addCase(refreshToken.rejected, (state, action) => { |
| state.loading = false; |
| state.error = action.payload ? action.payload : '' |
| }); |
| }, |
| |
| }); |
| |
| export default authSlice.reducer; |