import { hash } from 'ohash' import type { FetchOptions } from 'ofetch' import { useRuntimeConfig } from 'nuxt/app' import type { AppCookies, BaseResponse } from '#lib/types' import { getDeviceHeaders } from '#lib/utils/helper' interface IParam { key?: string // eslint-disable-next-line @typescript-eslint/no-explicit-any [key: string]: any } export function useApiFetch() { const API_URL = useRuntimeConfig().public.API_URL const $appCookies = useNuxtApp().$appCookies as AppCookies const { os, device, browser } = getDeviceHeaders() // eslint-disable-next-line @typescript-eslint/no-unused-vars const request = async ( url: string, params?: IParam, ): Promise> => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const opts: any = { key: hash(['api-fetch', url, params]), retry: 0, baseURL: API_URL, headers: { accept: 'application/json', }, async onRequest({ options }: { options: FetchOptions }): Promise { options.headers = options.headers ?? {} options.headers = { ...options.headers, 'Content-Type': 'application/json', accept: 'application/json', os, device, browser, } const requestToken = $appCookies.token.value const requestGpToken = $appCookies.gpToken.value if (requestToken) { options.headers = { ...options.headers, token: requestToken, ...(requestGpToken ? { gpToken: requestGpToken } : {}), } } }, onResponseError(): void { //console.error('onResponseError', response) }, params, lazy: false, server: true, } const data = await $fetch(url, opts) const response = typeof data === 'string' ? JSON.parse(data) : data return response as BaseResponse } return { request, } }