Files
trpc-nuxt/src/runtime/plugin.ts
2022-12-20 20:13:48 -08:00

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>
}
}