-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.slice.ts
61 lines (55 loc) · 1.9 KB
/
auth.slice.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import type { RootState } from "store/rootReducer";
import { fetch } from "../../api";
import { fetchProfileBalance } from "./profile.slice";
interface AuthState {
isSessionFetched: boolean;
hasAnActiveSubscription: boolean;
features: string[];
}
const initialState: AuthState = {
isSessionFetched: false,
hasAnActiveSubscription: false,
features: [],
};
export const fetchActiveSubscription = createAsyncThunk('fetchActiveSubscription', async (payload, thunkApi) => {
try {
const {impersonate, retainId} = (thunkApi.getState() as RootState).profile;
const response: any = await fetch<string[]>(thunkApi, { method: 'GET', url: `/profile/${impersonate ? retainId : "current"}/subscriptions/active-features` });
thunkApi.dispatch(fetchProfileBalance({}))
if (response.status !== 200) throw new Error();
return response.data;
} catch (error) {
await thunkApi.dispatch(logout());
return [];
}
});
export const authSlice = createSlice({
name: "auth",
initialState,
reducers: {
logout: () => ({
...initialState,
isSessionFetched: true
}),
},
extraReducers: (builder) => {
builder
.addCase(fetchActiveSubscription.pending, (state) => {
state.isSessionFetched = false;
state.hasAnActiveSubscription = false;
state.features = [];
})
.addCase(fetchActiveSubscription.fulfilled, (state, actions) => {
state.isSessionFetched = true;
state.hasAnActiveSubscription = actions.payload.includes('l2-upload-report') && actions.payload.includes('l1-run');
state.features = actions.payload;
})
.addCase(fetchActiveSubscription.rejected, (state) => {
state.isSessionFetched = true;
state.hasAnActiveSubscription = false;
})
},
});
export const { logout } = authSlice.actions;
export default authSlice.reducer;