oFetch.ts 2.23 KB
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;
});