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:
Robert Soriano
2022-09-24 08:19:16 -07:00
committed by GitHub
3 changed files with 18 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

@@ -1,5 +1,6 @@
import * as trpc from '@trpc/client'
import { unref } from 'vue'
import { FetchError } from 'ohmyfetch'
import { useClientHeaders } from './client'
import { defineNuxtPlugin, useRequestHeaders, useRuntimeConfig } from '#app'
import type { router } from '~/server/trpc'
@@ -10,14 +11,28 @@ 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)
.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)