blob: f1ab2a01daf388577fedddc1a8c7c11efde6a4d2 [file] [log] [blame]
2230101462240ab2025-06-07 09:28:16 +08001import { createAsyncThunk, createSlice, type PayloadAction } from "@reduxjs/toolkit";
22301014bc4616f2025-06-03 16:59:44 +08002import type { AuthState } from "../../store/types";
2230101462240ab2025-06-07 09:28:16 +08003import type { LoginRequest } from "../../api/type";
4import authAPI from "../../api/authApi";
22301014bc4616f2025-06-03 16:59:44 +08005
6
7const initialState: AuthState = {
8 token: '',
9 loading: false,
10 isAuth: false,
2230101462240ab2025-06-07 09:28:16 +080011 error: ''
22301014bc4616f2025-06-03 16:59:44 +080012}
13
2230101462240ab2025-06-07 09:28:16 +080014export const loginUser = createAsyncThunk<
15 {token: string},
16 LoginRequest,
17 { rejectValue: string }
18>(
19 'auth/login',
20 async (loginRequest: LoginRequest, { rejectWithValue }) => {
21 try {
22 const response = await authAPI.login(loginRequest);
23 if(response.data.code == 0) {
24 return {token: response.data.data};
25 }
26 else
27 return rejectWithValue(response.data.message);
28 } catch {
29 return rejectWithValue('登录失败');
30 }
31 }
32);
33
34export const refreshToken = createAsyncThunk<
35 {token: string},
36 string,
37 { rejectValue: string }
38>(
39
40 'auth/refresh',
41 async (oldToken: string, { rejectWithValue }) => {
42 try {
43 const response = await authAPI.refreshToken(oldToken);
44 if(response.data.code == 0)
45 return {token: response.data.data};
46 else
47 return rejectWithValue(response.data.message);
48 } catch {
49 return rejectWithValue('刷新失败');
50 }
51 }
52);
53
22301014bc4616f2025-06-03 16:59:44 +080054const authSlice = createSlice({
55 name: 'auth',
56 initialState,
2230101462240ab2025-06-07 09:28:16 +080057 reducers: {
58 logout: (state) => {
59 state.token = '';
60 state.isAuth = false;
61 localStorage.clear()
62 },
63 },extraReducers: (builder) => {
64 // 处理登录的异步操作
65 builder
66 .addCase(loginUser.pending, (state) => {
67 state.loading = true;
68 })
69 .addCase(loginUser.fulfilled, (state, action: PayloadAction<{token: string}>) => {
70 state.loading = false;
71 state.token = action.payload.token;
72 state.isAuth = true;
73
74 localStorage.setItem('token', state.token);
75 })
76 .addCase(loginUser.rejected, (state, action) => {
77 state.loading = false;
78 state.error = action.payload ? action.payload : '' // 错误处理
79 })
80
81 // 处理刷新 token 的异步操作
82 .addCase(refreshToken.pending, (state) => {
83 state.loading = true;
84 })
85 .addCase(refreshToken.fulfilled, (state, action) => {
86 state.loading = false;
87 state.token = action.payload.token;
88 localStorage.setItem('token', state.token);
89 })
90 .addCase(refreshToken.rejected, (state, action) => {
91 state.loading = false;
92 state.error = action.payload ? action.payload : ''
93 });
94 },
95
22301014bc4616f2025-06-03 16:59:44 +080096});
97
98export default authSlice.reducer;