-
Notifications
You must be signed in to change notification settings - Fork 0
/
usePermissions.ts
87 lines (76 loc) · 2.35 KB
/
usePermissions.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import { useEffect, useState, useRef, useMemo } from 'react'
import produce from 'immer'
import { useSimpleQuery } from '@interface-technologies/iti-react'
import { ConvenientGet } from './convenientGet'
export interface Options<T> {
query: T
onReady(permissions: { [K in keyof T]: boolean }): void
}
export type UsePermissions<TQueryTuple> = <
T extends { [key: string]: TQueryTuple | undefined }
>(
options: Options<T>
) => { [K in keyof T]: boolean }
/* eslint-disable react-hooks/rules-of-hooks -- does not understand the factory function */
/**
* Use the factory to get a React hook:
* ```
* const usePermissions = usePermissionsFactory<AppPermissionsQueryTuple>(
* api.appPermissions.get
* )
* ```
*
* In a component:
* ```
* const query = useMemo(() => ({
* canViewAudit: [PermissionName.CanViewAudit]
* }), [])
*
* const { canViewAudit } = usePermissions(
* query,
* onReady: () => {
* // do something
* },
* )
* ```
*/
export function usePermissionsFactory<TQueryTuple>(
convenientGet: ConvenientGet<TQueryTuple>
): UsePermissions<TQueryTuple> {
return <T extends { [key: string]: TQueryTuple | undefined }>({
query,
onReady,
}: Options<T>) => {
const defaultValue: { [key: string]: boolean } = {}
for (const key of Object.keys(query)) {
defaultValue[key] = false
}
const [permissions, setPermissions] = useState<{ [K in keyof T]: boolean }>(
defaultValue as { [K in keyof T]: boolean }
)
const onReadyRef = useRef(onReady)
useEffect(() => {
onReadyRef.current = onReady
})
const filteredQuery = useMemo(
() =>
produce(query, (draft) => {
const keys = Array.from(Object.keys(draft))
for (const key of keys) {
if (!draft[key]) delete draft[key]
}
}),
[query]
)
useSimpleQuery<T, { [K in keyof T]: boolean }>({
queryParams: filteredQuery,
query: convenientGet,
shouldQueryImmediately: () => true,
onResultReceived: (permissions) => {
setPermissions(permissions)
onReadyRef.current(permissions)
},
})
return permissions
}
}