mirror of
https://github.com/ArthurDanjou/trpc-nuxt.git
synced 2026-01-28 19:00:33 +01:00
Merge pull request #28 from robinWongM/feature/direct-api-call-during-ssr
feat: use globalThis.$fetch to call API handler directly on server-side
This commit is contained in:
@@ -5,7 +5,7 @@ import Module from '../src/module'
|
|||||||
export default defineNuxtConfig({
|
export default defineNuxtConfig({
|
||||||
modules: [Module],
|
modules: [Module],
|
||||||
runtimeConfig: {
|
runtimeConfig: {
|
||||||
baseURL: 'http://localhost:3000',
|
baseURL: '',
|
||||||
},
|
},
|
||||||
typescript: {
|
typescript: {
|
||||||
strict: true,
|
strict: true,
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ export default defineNuxtModule<ModuleOptions>({
|
|||||||
configKey: 'trpc',
|
configKey: 'trpc',
|
||||||
},
|
},
|
||||||
defaults: {
|
defaults: {
|
||||||
baseURL: 'http://localhost:3000',
|
baseURL: '',
|
||||||
endpoint: '/trpc',
|
endpoint: '/trpc',
|
||||||
},
|
},
|
||||||
async setup(options, nuxt) {
|
async setup(options, nuxt) {
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import * as trpc from '@trpc/client'
|
import * as trpc from '@trpc/client'
|
||||||
import { unref } from 'vue'
|
import { unref } from 'vue'
|
||||||
|
import { FetchError } from 'ohmyfetch'
|
||||||
import { useClientHeaders } from './client'
|
import { useClientHeaders } from './client'
|
||||||
import { defineNuxtPlugin, useRequestHeaders, useRuntimeConfig } from '#app'
|
import { defineNuxtPlugin, useRequestHeaders, useRuntimeConfig } from '#app'
|
||||||
import type { router } from '~/server/trpc'
|
import type { router } from '~/server/trpc'
|
||||||
@@ -10,14 +11,28 @@ export default defineNuxtPlugin((nuxtApp) => {
|
|||||||
const config = useRuntimeConfig().public.trpc
|
const config = useRuntimeConfig().public.trpc
|
||||||
const headers = useRequestHeaders()
|
const headers = useRequestHeaders()
|
||||||
const otherHeaders = useClientHeaders()
|
const otherHeaders = useClientHeaders()
|
||||||
|
|
||||||
|
const baseURL = process.server ? '' : config.baseURL
|
||||||
const client = trpc.createTRPCClient<AppRouter>({
|
const client = trpc.createTRPCClient<AppRouter>({
|
||||||
url: `${config.baseURL}${config.endpoint}`,
|
url: `${baseURL}${config.endpoint}`,
|
||||||
headers: () => {
|
headers: () => {
|
||||||
return {
|
return {
|
||||||
...unref(otherHeaders),
|
...unref(otherHeaders),
|
||||||
...headers,
|
...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)
|
nuxtApp.provide('client', client)
|
||||||
|
|||||||
Reference in New Issue
Block a user