feat: use globalThis.$fetch to call API handler directly on server-side

This commit is contained in:
Robin Wong
2022-09-16 16:37:39 +00:00
parent cdf29bee67
commit ee3ee485ba
3 changed files with 10 additions and 3 deletions

View File

@@ -5,7 +5,7 @@ import Module from '../src/module'
export default defineNuxtConfig({
modules: [Module],
runtimeConfig: {
baseURL: 'http://localhost:3000',
baseURL: '',
},
typescript: {
strict: true,

View File

@@ -16,7 +16,7 @@ export default defineNuxtModule<ModuleOptions>({
configKey: 'trpc',
},
defaults: {
baseURL: 'http://localhost:3000',
baseURL: '',
endpoint: '/trpc',
},
async setup(options, nuxt) {

View File

@@ -10,14 +10,21 @@ 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: `${config.baseURL}${config.endpoint}`,
url: `${baseURL}${config.endpoint}`,
headers: () => {
return {
...unref(otherHeaders),
...headers,
}
},
fetch: (input, options) =>
globalThis.$fetch.raw(input.toString(), options).then(response => ({
...response,
json: () => Promise.resolve(response._data),
}))
})
nuxtApp.provide('client', client)