1
|
import { createAsyncThunk } from '@reduxjs/toolkit'
|
2
|
import axiosInstance from '../../api/api'
|
3
|
import {UsersDetailState} from "./userDetailSlice"
|
4
|
|
5
|
|
6
|
const apiError = 'Error, server is currently unavailable.'
|
7
|
|
8
|
export const fetchUsers = createAsyncThunk(
|
9
|
'usersDetail/fetchUsers',
|
10
|
async (dispatch, { getState }) => {
|
11
|
try {
|
12
|
const {data, status} = await axiosInstance.get(
|
13
|
`/users`
|
14
|
)
|
15
|
if (status === 200) {
|
16
|
return data
|
17
|
}
|
18
|
return Promise.reject(apiError)
|
19
|
} catch (err: any) {
|
20
|
return Promise.reject(apiError)
|
21
|
}
|
22
|
}
|
23
|
)
|
24
|
|
25
|
export const savePermissions = createAsyncThunk(
|
26
|
'usersDetail/savePermissions',
|
27
|
async (dispatch, { getState }) => {
|
28
|
try {
|
29
|
const { usersDetail } = getState() as { usersDetail: UsersDetailState }
|
30
|
|
31
|
const selectedUser = usersDetail.selectedUser
|
32
|
if (selectedUser === undefined) {
|
33
|
return Promise.reject("User is undefined")
|
34
|
}
|
35
|
|
36
|
const selectedUserPermissions = usersDetail.permissions
|
37
|
if (selectedUserPermissions === undefined) {
|
38
|
return Promise.reject("Permissions is undefined")
|
39
|
}
|
40
|
|
41
|
const selectedUserIdentifier = selectedUser.email
|
42
|
|
43
|
const {data, status} = await axiosInstance.patch(
|
44
|
`/users/${selectedUserIdentifier}/permissions`,
|
45
|
selectedUserPermissions
|
46
|
)
|
47
|
if (status === 200) {
|
48
|
return data
|
49
|
}
|
50
|
return Promise.reject(apiError)
|
51
|
} catch (err: any) {
|
52
|
return Promise.reject(apiError)
|
53
|
}
|
54
|
}
|
55
|
)
|
56
|
|
57
|
export const deleteUser = createAsyncThunk(
|
58
|
'usersDetail/deleteUser',
|
59
|
async (dispatch, { getState }) => {
|
60
|
const { usersDetail } = getState() as { usersDetail: UsersDetailState }
|
61
|
|
62
|
const selectedUser = usersDetail.selectedUser
|
63
|
|
64
|
if (selectedUser === undefined) {
|
65
|
return Promise.reject("User is undefined")
|
66
|
}
|
67
|
const { data, status } = await axiosInstance.delete(
|
68
|
`/users/${selectedUser?.email}`
|
69
|
)
|
70
|
if (status !== 200) {
|
71
|
// TODO dodělat zpracování erroru
|
72
|
return Promise.reject("Deleting user failed")
|
73
|
}
|
74
|
return status
|
75
|
}
|
76
|
)
|