完善验证页面和后端接口的链接
> 1. 配置了开发环境的端口转发 -> localhost:8080\
> 2. 完成了注册,登录,忘记密码页的功能
> 3. 为项目配置了vitest测试框架
> 4. 对这三个页面进行了测试
> 重写了/test/setup.ts
Change-Id: I46c600ce06d698dae6953b2e1e3ff4a98b0f3de4
diff --git a/src/feature/auth/authSlice.ts b/src/feature/auth/authSlice.ts
index 01cd4e5..f1ab2a0 100644
--- a/src/feature/auth/authSlice.ts
+++ b/src/feature/auth/authSlice.ts
@@ -1,17 +1,98 @@
-import { createSlice } from "@reduxjs/toolkit";
+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: {},
+ 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;
\ No newline at end of file