oFetch.ts
2.23 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
import type { $Fetch } from "nitropack";
import type { RuntimeConfig } from "nuxt/schema";
import { ofetch } from "ofetch";
/**
* Ce plugin est essentiel !
* Il sert à paramétrer 'ofetch' qui est d'office utilisé par Nuxt à l'initialisation de notre app.
* (Sert par exemple pour toutes les méthodes liées au provider d'authentification).
*/
export default defineNuxtPlugin(async (_nuxtApp) => {
// Récupération des variables d'environnement (hydratées dans le nuxt.config.ts).
const runtimeConfig: RuntimeConfig = useRuntimeConfig();
// On rend la configuration que l'on crée globale grâce à 'globalThis.$fetch'.
globalThis.$fetch = ofetch.create({
/**
* Request interceptor.
*/
onRequest({ request, options }) {
if (typeof request === "string" && request.includes("movie")) {
/** empty */
// Set the baseURL to the TMDB API URL.
// Base url example : https://nom-de-domaine/something.
options.baseURL = runtimeConfig.public.apiTMDBUrl;
// Set the request headers
// note that this relies on ofetch >= 1.4.0 - you may need to refresh your lockfile.
options.headers.set("Authorization", `Bearer ${runtimeConfig.public.apiTMDBBearer}`);
}
},
/**
* Request error interceptor.
*/
onRequestError({ request, options, error }) {
// Handle the request errors
// Do something before request error sent.
if (request) { /** empty */ }
if (options) { /** empty */ }
if (error) { /** empty */ }
},
/**
* Response interceptor.
*/
onResponse({ request, response, options }) {
// Process the response data
if (request) { /** empty */ }
if (response) { /** empty */ }
// If response return 401 code.
// if (
// (response && response.code && response.code === 401)
// || (response && response.status && response.status === 401)
// ) {
// // Do something if 401.
// }
if (options) { /** empty */ }
},
onResponseError({ request, response, options }) {
// Handle the response errors
if (request) { /** empty */ }
if (response) { /** empty */ }
if (options) { /** empty */ }
},
}) as unknown as $Fetch;
});