-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
index.ts
62 lines (55 loc) · 1.52 KB
/
index.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
import type { ComputedRef } from 'vue-demi'
import { computed } from 'vue-demi'
import type { MaybeRefOrGetter } from '@vueuse/shared'
import { toValue } from '@vueuse/shared'
import { jwtDecode } from 'jwt-decode'
import type { JwtDecodeOptions, JwtHeader, JwtPayload } from 'jwt-decode'
export interface UseJwtOptions<Fallback> {
/**
* Value returned when encounter error on decoding
*
* @default null
*/
fallbackValue?: Fallback
/**
* Error callback for decoding
*/
onError?: (error: unknown) => void
}
export interface UseJwtReturn<Payload, Header, Fallback> {
header: ComputedRef<Header | Fallback>
payload: ComputedRef<Payload | Fallback>
}
/**
* Reactive decoded jwt token.
*
* @see https://vueuse.org/useJwt
*/
export function useJwt<
Payload extends object = JwtPayload,
Header extends object = JwtHeader,
Fallback = null,
>(
encodedJwt: MaybeRefOrGetter<string>,
options: UseJwtOptions<Fallback> = {},
): UseJwtReturn<Payload, Header, Fallback> {
const {
onError,
fallbackValue = null,
} = options
const decodeWithFallback = <T extends object>(encodedJwt: string, options?: JwtDecodeOptions): T | Fallback => {
try {
return jwtDecode<T>(encodedJwt, options)
}
catch (err) {
onError?.(err)
return fallbackValue as Fallback
}
}
const header = computed(() => decodeWithFallback<Header>(toValue(encodedJwt), { header: true }))
const payload = computed(() => decodeWithFallback<Payload>(toValue(encodedJwt)))
return {
header,
payload,
}
}