-
Notifications
You must be signed in to change notification settings - Fork 90
Expand file tree
/
Copy pathuseStrapiClient.ts
More file actions
84 lines (75 loc) · 2.04 KB
/
useStrapiClient.ts
File metadata and controls
84 lines (75 loc) · 2.04 KB
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
import type { FetchError, FetchOptions } from 'ofetch'
import { stringify } from 'qs'
import type { Strapi4Error } from '../types/v4'
import type { Strapi3Error } from '../types/v3'
import { useStrapiUrl } from './useStrapiUrl'
import { useStrapiVersion } from './useStrapiVersion'
import { useStrapiToken } from './useStrapiToken'
import { useNuxtApp } from '#imports'
const defaultErrors = (err: FetchError) => ({
v4: {
error: {
status: 500,
name: 'UnknownError',
message: err.message,
details: err
}
},
v3: {
error: 'UnknownError',
message: err.message,
statusCode: 500
}
})
const fallbackError = (err: FetchError) => ({
error: {
status: err.statusCode || 500,
name: err.name || 'UnknownError',
message: err.message || 'UnknownError',
details: err
}
})
export const useStrapiClient = () => {
const nuxt = useNuxtApp()
const baseURL = useStrapiUrl()
const version = useStrapiVersion()
const token = useStrapiToken()
return async <T> (url: string, fetchOptions: FetchOptions = {}): Promise<T> => {
const headers: HeadersInit = {}
if (token && token.value) {
headers.Authorization = `Bearer ${token.value}`
}
// Map params according to strapi v3 and v4 formats
if (fetchOptions.params) {
const params = stringify(fetchOptions.params, { encodeValuesOnly: true })
if (params) {
url = `${url}?${params}`
}
delete fetchOptions.params
}
try {
// @ts-expect-error method is not explicitly typed
return await $fetch<T>(url, {
retry: 0,
baseURL,
...fetchOptions,
headers: {
...headers,
...fetchOptions.headers
}
})
} catch (err) {
const e: Strapi4Error | Strapi3Error
= err.data
|| defaultErrors(err)[version]
|| fallbackError(err)
nuxt.hooks.callHook('strapi:error', e)
throw e
}
}
}
declare module '#app' {
interface RuntimeNuxtHooks {
'strapi:error': (error: Strapi3Error | Strapi4Error) => void
}
}