mirror of
https://github.com/ArthurDanjou/trpc-nuxt.git
synced 2026-01-14 20:19:33 +01:00
refactor: plugin arrangement
This commit is contained in:
@@ -2,7 +2,7 @@ import { fileURLToPath } from 'url'
|
||||
import { join, resolve } from 'pathe'
|
||||
import { defu } from 'defu'
|
||||
|
||||
import { addPluginTemplate, addServerHandler, addTemplate, defineNuxtModule } from '@nuxt/kit'
|
||||
import { addPlugin, addServerHandler, addTemplate, defineNuxtModule } from '@nuxt/kit'
|
||||
|
||||
export interface ModuleOptions {
|
||||
baseURL: string
|
||||
@@ -33,7 +33,7 @@ export default defineNuxtModule<ModuleOptions>({
|
||||
|
||||
nuxt.hook('autoImports:extend', (imports) => {
|
||||
imports.push(
|
||||
{ name: 'useClient', from: '#build/trpc-client' },
|
||||
{ name: 'useClient', from: join(runtimeDir, 'client') },
|
||||
{ name: 'useAsyncQuery', from: join(runtimeDir, 'client') },
|
||||
)
|
||||
})
|
||||
@@ -43,26 +43,7 @@ export default defineNuxtModule<ModuleOptions>({
|
||||
handler: handlerPath,
|
||||
})
|
||||
|
||||
addTemplate({
|
||||
filename: 'trpc-client.ts',
|
||||
write: true,
|
||||
getContents() {
|
||||
return `
|
||||
export const useClient = () => {
|
||||
const { $client } = useNuxtApp()
|
||||
return $client
|
||||
}
|
||||
`
|
||||
},
|
||||
})
|
||||
|
||||
addPluginTemplate({
|
||||
src: resolve(runtimeDir, 'plugin.ts'),
|
||||
write: true,
|
||||
options: {
|
||||
url: `${finalConfig.baseURL}${finalConfig.trpcURL}`,
|
||||
},
|
||||
})
|
||||
addPlugin(resolve(runtimeDir, 'plugin'))
|
||||
|
||||
addTemplate({
|
||||
filename: 'trpc-handler.ts',
|
||||
|
||||
@@ -58,3 +58,8 @@ export async function useAsyncQuery<
|
||||
error: serverError,
|
||||
} as any
|
||||
}
|
||||
|
||||
export function useClient() {
|
||||
const { $client } = useNuxtApp()
|
||||
return $client
|
||||
}
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import * as trpc from '@trpc/client'
|
||||
import { defineNuxtPlugin, useRequestHeaders } from '#app'
|
||||
// @ts-expect-error: Resolved by Nuxt
|
||||
import { defineNuxtPlugin, useRequestHeaders, useRuntimeConfig } from '#app'
|
||||
// @ts-expect-error: Resolved by Nuxt
|
||||
import type { router } from '~/server/trpc'
|
||||
|
||||
const options = JSON.parse('<%= JSON.stringify(options) %>')
|
||||
|
||||
export default defineNuxtPlugin(() => {
|
||||
const config = useRuntimeConfig().public.trpc
|
||||
const client = trpc.createTRPCClient<typeof router>({
|
||||
url: options.url as string,
|
||||
url: `${config.baseURL}${config.trpcURL}`,
|
||||
headers: useRequestHeaders(),
|
||||
})
|
||||
|
||||
|
||||
Reference in New Issue
Block a user