mirror of
https://github.com/ArthurDanjou/trpc-nuxt.git
synced 2026-01-14 20:19:33 +01:00
46 lines
1.2 KiB
TypeScript
46 lines
1.2 KiB
TypeScript
import * as trpc from '@trpc/client'
|
|
import { unref } from 'vue'
|
|
import { FetchError } from 'ofetch'
|
|
import { useClientHeaders } from './client'
|
|
import { defineNuxtPlugin, useRequestHeaders, useRuntimeConfig } from '#imports'
|
|
import type { router } from '~/server/trpc'
|
|
|
|
declare type AppRouter = typeof router
|
|
|
|
export default defineNuxtPlugin((nuxtApp) => {
|
|
const config = useRuntimeConfig().public.trpc
|
|
const headers = useRequestHeaders()
|
|
const otherHeaders = useClientHeaders()
|
|
|
|
const baseURL = process.server ? '' : config.baseURL
|
|
const client = trpc.createTRPCClient<AppRouter>({
|
|
url: `${baseURL}${config.endpoint}`,
|
|
headers: () => {
|
|
return {
|
|
...unref(otherHeaders),
|
|
...headers,
|
|
}
|
|
},
|
|
fetch: (input, options) =>
|
|
globalThis.$fetch.raw(input.toString(), options)
|
|
.catch((e) => {
|
|
if (e instanceof FetchError && e.response)
|
|
return e.response
|
|
|
|
throw e
|
|
})
|
|
.then(response => ({
|
|
...response,
|
|
json: () => Promise.resolve(response._data),
|
|
})),
|
|
})
|
|
|
|
nuxtApp.provide('client', client)
|
|
})
|
|
|
|
declare module '#app' {
|
|
interface NuxtApp {
|
|
$client: trpc.TRPCClient<AppRouter>
|
|
}
|
|
}
|