mirror of
https://github.com/ArthurDanjou/trpc-nuxt.git
synced 2026-01-22 16:00:37 +01:00
Compare commits
61 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
07693009f8 | ||
|
|
dceade155c | ||
|
|
4012249f09 | ||
|
|
38eda2c4d6 | ||
|
|
9468af75f4 | ||
|
|
ea24a67a6d | ||
|
|
5e8d04741c | ||
|
|
1032e65a0d | ||
|
|
f261d3feeb | ||
|
|
b1ca09e986 | ||
|
|
b804429fc0 | ||
|
|
7df64296ff | ||
|
|
a53d823f5e | ||
|
|
feef3dde6b | ||
|
|
82ee2ce672 | ||
|
|
f62a13766a | ||
|
|
c7888e81ed | ||
|
|
c77eb68f5d | ||
|
|
333539569c | ||
|
|
e5c40f183b | ||
|
|
977a9e1465 | ||
|
|
2620379e02 | ||
|
|
e4f42d5322 | ||
|
|
ad28a9124e | ||
|
|
273bda980b | ||
|
|
9c8509f79c | ||
|
|
2ce29137ce | ||
|
|
e9c5307e23 | ||
|
|
bbdabf544c | ||
|
|
aed10ac5b8 | ||
|
|
4b2c714658 | ||
|
|
43e9fefdbd | ||
|
|
dabda23976 | ||
|
|
af89f32275 | ||
|
|
1f27b871fb | ||
|
|
281e4c05a0 | ||
|
|
38ac520b97 | ||
|
|
96ebff619e | ||
|
|
f668e4a9b4 | ||
|
|
58b0165557 | ||
|
|
3b5e35ef68 | ||
|
|
48152ead8d | ||
|
|
7f44e049c0 | ||
|
|
5a71bbf1fe | ||
|
|
285487e9bf | ||
|
|
2cfa64fcc6 | ||
|
|
eea5733dcd | ||
|
|
71bbbf2b86 | ||
|
|
2b57ab8791 | ||
|
|
f8edd769f0 | ||
|
|
419ef34de6 | ||
|
|
30c76b5859 | ||
|
|
2575beae5d | ||
|
|
b09d1af30d | ||
|
|
610e441db7 | ||
|
|
959b370729 | ||
|
|
c1c4e67694 | ||
|
|
779221d9e6 | ||
|
|
986b661e99 | ||
|
|
77325a6699 | ||
|
|
6dcb4ce8a6 |
19
README.md
19
README.md
@@ -29,10 +29,10 @@ export default defineNuxtConfig({
|
|||||||
modules: ['trpc-nuxt'],
|
modules: ['trpc-nuxt'],
|
||||||
trpc: {
|
trpc: {
|
||||||
baseURL: 'http://localhost:3000', // defaults to http://localhost:3000
|
baseURL: 'http://localhost:3000', // defaults to http://localhost:3000
|
||||||
trpcURL: '/api/trpc', // defaults to /api/trpc
|
endpoint: '/trpc', // defaults to /trpc
|
||||||
},
|
},
|
||||||
typescript: {
|
typescript: {
|
||||||
strict: true // set this to true to make input/output types work
|
strict: true // required to make input/output types work
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
```
|
```
|
||||||
@@ -99,6 +99,21 @@ const {
|
|||||||
})
|
})
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## useClientHeaders
|
||||||
|
|
||||||
|
A composable that lets you add additional properties to pass to the tRPC Client. It uses `useStorage` from [@vueuse/core](https://vueuse.org/core/usestorage).
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const headers = useClientHeaders()
|
||||||
|
|
||||||
|
const { data: token } = await useAsyncQuery(['auth.login', { username, password }])
|
||||||
|
|
||||||
|
headers.value.Authorization = `Bearer ${token}`
|
||||||
|
|
||||||
|
// All client calls will now include the Authorization header.
|
||||||
|
// For SSR, please follow this link https://github.com/trpc/trpc/discussions/1686
|
||||||
|
```
|
||||||
|
|
||||||
## Options
|
## Options
|
||||||
|
|
||||||
trpc-nuxt accepts the following options exposed under `~/server/trpc/index.ts`:
|
trpc-nuxt accepts the following options exposed under `~/server/trpc/index.ts`:
|
||||||
|
|||||||
21
package.json
21
package.json
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "trpc-nuxt",
|
"name": "trpc-nuxt",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"version": "0.1.7",
|
"version": "0.2.2",
|
||||||
"packageManager": "pnpm@7.1.1",
|
"packageManager": "pnpm@7.1.1",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"main": "./dist/module.cjs",
|
"main": "./dist/module.cjs",
|
||||||
@@ -32,11 +32,14 @@
|
|||||||
"prepare": "nuxi prepare playground"
|
"prepare": "nuxi prepare playground"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@nuxt/kit": "^3.0.0-rc.3",
|
"@nuxt/kit": "^3.0.0-rc.4",
|
||||||
"@trpc/client": "^9.23.3",
|
"@trpc/client": "^9.25.2",
|
||||||
"@trpc/server": "^9.23.2",
|
"@trpc/server": "^9.25.2",
|
||||||
|
"@vueuse/core": "^8.6.0",
|
||||||
|
"@vueuse/nuxt": "^8.6.0",
|
||||||
|
"dedent": "^0.7.0",
|
||||||
"defu": "^6.0.0",
|
"defu": "^6.0.0",
|
||||||
"h3": "^0.7.8",
|
"h3": "^0.7.9",
|
||||||
"pathe": "^0.3.0",
|
"pathe": "^0.3.0",
|
||||||
"ufo": "^0.8.4"
|
"ufo": "^0.8.4"
|
||||||
},
|
},
|
||||||
@@ -46,14 +49,16 @@
|
|||||||
"@nuxt/module-builder": "latest",
|
"@nuxt/module-builder": "latest",
|
||||||
"bumpp": "^7.1.1",
|
"bumpp": "^7.1.1",
|
||||||
"eslint": "^8.14.0",
|
"eslint": "^8.14.0",
|
||||||
"nuxt": "^3.0.0-rc.3",
|
"nuxt": "3.0.0-rc.4",
|
||||||
"ohash": "^0.1.0",
|
"ohash": "^0.1.0",
|
||||||
"pnpm": "^7.1.1",
|
"pnpm": "^7.1.1",
|
||||||
"superjson": "^1.9.1",
|
|
||||||
"trpc-nuxt": "workspace:*",
|
"trpc-nuxt": "workspace:*",
|
||||||
"zod": "^3.16.0"
|
"zod": "^3.16.0"
|
||||||
},
|
},
|
||||||
"eslintConfig": {
|
"eslintConfig": {
|
||||||
"extends": "@antfu"
|
"extends": "@antfu",
|
||||||
|
"rules": {
|
||||||
|
"no-console": "warn"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
19
playground/pages/cookie.vue
Normal file
19
playground/pages/cookie.vue
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
const counter = useCookie('counter')
|
||||||
|
counter.value = counter.value || Math.round(Math.random() * 1000)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div>
|
||||||
|
<h1> Counter: {{ counter || '-' }}</h1>
|
||||||
|
<button @click="counter = null">
|
||||||
|
reset
|
||||||
|
</button>
|
||||||
|
<button @click="counter--">
|
||||||
|
-
|
||||||
|
</button>
|
||||||
|
<button @click="counter++">
|
||||||
|
+
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -1,7 +1,13 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
const client = useClient()
|
const client = useClient()
|
||||||
|
const headers = useClientHeaders()
|
||||||
const { data: todos, pending, error, refresh } = await useAsyncQuery(['getTodos'])
|
const { data: todos, pending, error, refresh } = await useAsyncQuery(['getTodos'])
|
||||||
|
|
||||||
|
const addHeader = () => {
|
||||||
|
// headers.value.cookie = 'counter=69'
|
||||||
|
console.log(headers.value)
|
||||||
|
}
|
||||||
|
|
||||||
const addTodo = async () => {
|
const addTodo = async () => {
|
||||||
const title = Math.random().toString(36).slice(2, 7)
|
const title = Math.random().toString(36).slice(2, 7)
|
||||||
|
|
||||||
@@ -27,7 +33,7 @@ const addTodo = async () => {
|
|||||||
<div v-else-if="error?.data?.code">
|
<div v-else-if="error?.data?.code">
|
||||||
Error: {{ error.data.code }}
|
Error: {{ error.data.code }}
|
||||||
</div>
|
</div>
|
||||||
<div v-else>
|
<div v-else-if="todos">
|
||||||
<ul>
|
<ul>
|
||||||
<li v-for="t in todos.slice(0, 10)" :key="t.id">
|
<li v-for="t in todos.slice(0, 10)" :key="t.id">
|
||||||
<NuxtLink :class="{ completed: t.completed }" :to="`/todo/${t.id}`">
|
<NuxtLink :class="{ completed: t.completed }" :to="`/todo/${t.id}`">
|
||||||
@@ -41,6 +47,9 @@ const addTodo = async () => {
|
|||||||
<button @click="() => refresh()">
|
<button @click="() => refresh()">
|
||||||
Refresh
|
Refresh
|
||||||
</button>
|
</button>
|
||||||
|
<button @click="addHeader">
|
||||||
|
Add header
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import * as trpc from '@trpc/server'
|
import * as trpc from '@trpc/server'
|
||||||
|
import type { inferAsyncReturnType } from '@trpc/server'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
|
import type { CompatibilityEvent } from 'h3'
|
||||||
|
|
||||||
const baseURL = 'https://jsonplaceholder.typicode.com'
|
const baseURL = 'https://jsonplaceholder.typicode.com'
|
||||||
|
|
||||||
@@ -12,7 +14,7 @@ const TodoShape = z.object({
|
|||||||
|
|
||||||
export type Todo = z.infer<typeof TodoShape>
|
export type Todo = z.infer<typeof TodoShape>
|
||||||
|
|
||||||
export const router = trpc.router()
|
export const router = trpc.router<Context>()
|
||||||
.query('getTodos', {
|
.query('getTodos', {
|
||||||
async resolve() {
|
async resolve() {
|
||||||
return await $fetch<Todo[]>(`${baseURL}/todos`)
|
return await $fetch<Todo[]>(`${baseURL}/todos`)
|
||||||
@@ -27,9 +29,25 @@ export const router = trpc.router()
|
|||||||
.mutation('addTodo', {
|
.mutation('addTodo', {
|
||||||
input: TodoShape,
|
input: TodoShape,
|
||||||
async resolve(req) {
|
async resolve(req) {
|
||||||
|
console.log(req.input)
|
||||||
return await $fetch<Todo>(`${baseURL}/todos`, {
|
return await $fetch<Todo>(`${baseURL}/todos`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: req.input,
|
body: req.input,
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
export async function createContext(event: CompatibilityEvent) {
|
||||||
|
// Create your context based on the request object
|
||||||
|
// Will be available as `ctx` in all your resolvers
|
||||||
|
|
||||||
|
// This is just an example of something you'd might want to do in your ctx fn
|
||||||
|
// const x = useCookies(event)
|
||||||
|
console.log(event.req.headers)
|
||||||
|
|
||||||
|
return {
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type Context = inferAsyncReturnType<typeof createContext>
|
||||||
|
|||||||
2103
pnpm-lock.yaml
generated
2103
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -1,12 +1,14 @@
|
|||||||
import { fileURLToPath } from 'url'
|
import { fileURLToPath } from 'url'
|
||||||
import { join } from 'pathe'
|
import { join, resolve } from 'pathe'
|
||||||
import { defu } from 'defu'
|
import { defu } from 'defu'
|
||||||
|
// @ts-expect-error: No types
|
||||||
|
import dedent from 'dedent'
|
||||||
|
|
||||||
import { addServerHandler, addTemplate, defineNuxtModule } from '@nuxt/kit'
|
import { addAutoImport, addPlugin, addServerHandler, addTemplate, defineNuxtModule } from '@nuxt/kit'
|
||||||
|
|
||||||
export interface ModuleOptions {
|
export interface ModuleOptions {
|
||||||
baseURL: string
|
baseURL: string
|
||||||
trpcURL: string
|
endpoint: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export default defineNuxtModule<ModuleOptions>({
|
export default defineNuxtModule<ModuleOptions>({
|
||||||
@@ -16,64 +18,49 @@ export default defineNuxtModule<ModuleOptions>({
|
|||||||
},
|
},
|
||||||
defaults: {
|
defaults: {
|
||||||
baseURL: 'http://localhost:3000',
|
baseURL: 'http://localhost:3000',
|
||||||
trpcURL: '/api/trpc',
|
endpoint: '/trpc',
|
||||||
},
|
},
|
||||||
async setup(options, nuxt) {
|
async setup(options, nuxt) {
|
||||||
const runtimeDir = fileURLToPath(new URL('./runtime', import.meta.url))
|
const runtimeDir = fileURLToPath(new URL('./runtime', import.meta.url))
|
||||||
nuxt.options.build.transpile.push(runtimeDir, '#build/trpc-client', '#build/trpc-handler', '#build/trpc-helpers')
|
nuxt.options.build.transpile.push(runtimeDir, '#build/trpc-handler')
|
||||||
|
|
||||||
const handlerPath = join(nuxt.options.buildDir, 'trpc-handler.ts')
|
const handlerPath = join(nuxt.options.buildDir, 'trpc-handler.ts')
|
||||||
const trpcOptionsPath = join(nuxt.options.rootDir, 'server/trpc')
|
const trpcOptionsPath = join(nuxt.options.srcDir, 'server/trpc')
|
||||||
|
|
||||||
|
// Add vueuse
|
||||||
|
nuxt.options.modules.push('@vueuse/nuxt')
|
||||||
|
|
||||||
// Final resolved configuration
|
// Final resolved configuration
|
||||||
const finalConfig = nuxt.options.runtimeConfig.public.trpc = defu(nuxt.options.runtimeConfig.public.trpc, {
|
const finalConfig = nuxt.options.runtimeConfig.public.trpc = defu(nuxt.options.runtimeConfig.public.trpc, {
|
||||||
baseURL: options.baseURL,
|
baseURL: options.baseURL,
|
||||||
trpcURL: options.trpcURL,
|
endpoint: options.endpoint,
|
||||||
})
|
})
|
||||||
|
|
||||||
nuxt.hook('autoImports:extend', (imports) => {
|
addAutoImport([
|
||||||
imports.push(
|
{ name: 'useClient', from: join(runtimeDir, 'client') },
|
||||||
{ name: 'useClient', from: '#build/trpc-client' },
|
{ name: 'useAsyncQuery', from: join(runtimeDir, 'client') },
|
||||||
{ name: 'useAsyncQuery', from: join(runtimeDir, 'client') },
|
{ name: 'useClientHeaders', from: join(runtimeDir, 'client') },
|
||||||
)
|
{ name: 'getQueryKey', from: join(runtimeDir, 'client') },
|
||||||
})
|
])
|
||||||
|
|
||||||
addServerHandler({
|
addServerHandler({
|
||||||
route: `${finalConfig.trpcURL}/*`,
|
route: `${finalConfig.endpoint}/*`,
|
||||||
handler: handlerPath,
|
handler: handlerPath,
|
||||||
})
|
})
|
||||||
|
|
||||||
addTemplate({
|
addPlugin(resolve(runtimeDir, 'plugin'))
|
||||||
filename: 'trpc-client.ts',
|
|
||||||
write: true,
|
|
||||||
getContents() {
|
|
||||||
return `
|
|
||||||
import * as trpc from '@trpc/client'
|
|
||||||
import type { router } from '${trpcOptionsPath}'
|
|
||||||
|
|
||||||
const client = trpc.createTRPCClient<typeof router>({
|
|
||||||
url: '${finalConfig.baseURL}${finalConfig.trpcURL}',
|
|
||||||
})
|
|
||||||
|
|
||||||
export const useClient = () => client
|
|
||||||
`
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
addTemplate({
|
addTemplate({
|
||||||
filename: 'trpc-handler.ts',
|
filename: 'trpc-handler.ts',
|
||||||
write: true,
|
write: true,
|
||||||
getContents() {
|
getContents() {
|
||||||
return `
|
return dedent`
|
||||||
import { createTRPCHandler } from 'trpc-nuxt/api'
|
import { createTRPCHandler } from 'trpc-nuxt/api'
|
||||||
import { useRuntimeConfig } from '#imports'
|
|
||||||
import * as functions from '${trpcOptionsPath}'
|
import * as functions from '${trpcOptionsPath}'
|
||||||
|
|
||||||
const { trpc: { trpcURL } } = useRuntimeConfig().public
|
|
||||||
|
|
||||||
export default createTRPCHandler({
|
export default createTRPCHandler({
|
||||||
...functions,
|
...functions,
|
||||||
trpcURL
|
endpoint: '${finalConfig.endpoint}'
|
||||||
})
|
})
|
||||||
`
|
`
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -42,13 +42,13 @@ export function createTRPCHandler<Router extends AnyRouter>({
|
|||||||
createContext,
|
createContext,
|
||||||
responseMeta,
|
responseMeta,
|
||||||
onError,
|
onError,
|
||||||
trpcURL,
|
endpoint,
|
||||||
}: {
|
}: {
|
||||||
router: Router
|
router: Router
|
||||||
createContext?: CreateContextFn<Router>
|
createContext?: CreateContextFn<Router>
|
||||||
responseMeta?: ResponseMetaFn<Router>
|
responseMeta?: ResponseMetaFn<Router>
|
||||||
onError?: OnErrorFn<Router>
|
onError?: OnErrorFn<Router>
|
||||||
trpcURL: string
|
endpoint: string
|
||||||
}) {
|
}) {
|
||||||
return defineEventHandler(async (event) => {
|
return defineEventHandler(async (event) => {
|
||||||
const {
|
const {
|
||||||
@@ -56,17 +56,17 @@ export function createTRPCHandler<Router extends AnyRouter>({
|
|||||||
res,
|
res,
|
||||||
} = event
|
} = event
|
||||||
|
|
||||||
const $url = createURL(req.url)
|
const $url = createURL(req.url!)
|
||||||
|
|
||||||
const httpResponse = await resolveHTTPResponse({
|
const httpResponse = await resolveHTTPResponse({
|
||||||
router,
|
router,
|
||||||
req: {
|
req: {
|
||||||
method: req.method,
|
method: req.method!,
|
||||||
headers: req.headers,
|
headers: req.headers,
|
||||||
body: isMethod(event, 'GET') ? null : await useBody(event),
|
body: isMethod(event, 'GET') ? null : await useBody(event),
|
||||||
query: $url.searchParams,
|
query: $url.searchParams,
|
||||||
},
|
},
|
||||||
path: $url.pathname.substring(trpcURL.length + 1),
|
path: $url.pathname.substring(endpoint.length + 1),
|
||||||
createContext: async () => createContext?.(event),
|
createContext: async () => createContext?.(event),
|
||||||
responseMeta,
|
responseMeta,
|
||||||
onError: (o) => {
|
onError: (o) => {
|
||||||
@@ -81,8 +81,8 @@ export function createTRPCHandler<Router extends AnyRouter>({
|
|||||||
|
|
||||||
res.statusCode = status
|
res.statusCode = status
|
||||||
|
|
||||||
Object.keys(headers).forEach((key) => {
|
headers && Object.keys(headers).forEach((key) => {
|
||||||
res.setHeader(key, headers[key])
|
res.setHeader(key, headers[key]!)
|
||||||
})
|
})
|
||||||
|
|
||||||
return body
|
return body
|
||||||
|
|||||||
@@ -6,13 +6,15 @@ import type {
|
|||||||
_Transform,
|
_Transform,
|
||||||
} from 'nuxt/dist/app/composables/asyncData'
|
} from 'nuxt/dist/app/composables/asyncData'
|
||||||
import type { ProcedureRecord, inferHandlerInput, inferProcedureInput, inferProcedureOutput } from '@trpc/server'
|
import type { ProcedureRecord, inferHandlerInput, inferProcedureInput, inferProcedureOutput } from '@trpc/server'
|
||||||
import type { TRPCClientErrorLike } from '@trpc/client'
|
import type { TRPCClient, TRPCClientErrorLike } from '@trpc/client'
|
||||||
import { objectHash } from 'ohash'
|
import { objectHash } from 'ohash'
|
||||||
import { useAsyncData, useState } from '#app'
|
import type { Ref } from 'vue'
|
||||||
import { useClient } from '#build/trpc-client'
|
import { useStorage } from '@vueuse/core'
|
||||||
// @ts-expect-error: Resolved by Nuxt
|
import { useAsyncData, useNuxtApp, useState } from '#app'
|
||||||
import type { router } from '~/server/trpc'
|
import type { router } from '~/server/trpc'
|
||||||
|
|
||||||
|
type MaybeRef<T> = T | Ref<T>
|
||||||
|
|
||||||
type AppRouter = typeof router
|
type AppRouter = typeof router
|
||||||
|
|
||||||
export type inferProcedures<
|
export type inferProcedures<
|
||||||
@@ -29,6 +31,16 @@ export type TError = TRPCClientErrorLike<AppRouter>
|
|||||||
|
|
||||||
export type TQueryValues = inferProcedures<AppRouter['_def']['queries']>
|
export type TQueryValues = inferProcedures<AppRouter['_def']['queries']>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calculates the key used for `useAsyncData` call
|
||||||
|
* @param pathAndInput
|
||||||
|
*/
|
||||||
|
export function getQueryKey<
|
||||||
|
TPath extends keyof TQueryValues & string,
|
||||||
|
>(pathAndInput: [path: TPath, ...args: inferHandlerInput<TQueries[TPath]>]) {
|
||||||
|
return `${pathAndInput[0]}-${objectHash(pathAndInput[1] ? JSON.stringify(pathAndInput[1]) : '')}`
|
||||||
|
}
|
||||||
|
|
||||||
export async function useAsyncQuery<
|
export async function useAsyncQuery<
|
||||||
TPath extends keyof TQueryValues & string,
|
TPath extends keyof TQueryValues & string,
|
||||||
TOutput extends TQueryValues[TPath]['output'] = TQueryValues[TPath]['output'],
|
TOutput extends TQueryValues[TPath]['output'] = TQueryValues[TPath]['output'],
|
||||||
@@ -38,12 +50,13 @@ export async function useAsyncQuery<
|
|||||||
pathAndInput: [path: TPath, ...args: inferHandlerInput<TQueries[TPath]>],
|
pathAndInput: [path: TPath, ...args: inferHandlerInput<TQueries[TPath]>],
|
||||||
options: AsyncDataOptions<TOutput, Transform, PickKeys> = {},
|
options: AsyncDataOptions<TOutput, Transform, PickKeys> = {},
|
||||||
): Promise<AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, TError>> {
|
): Promise<AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, TError>> {
|
||||||
const client = useClient()
|
const { $client } = useNuxtApp()
|
||||||
const key = `${pathAndInput[0]}-${objectHash(pathAndInput[1] ? JSON.stringify(pathAndInput[1]) : '')}`
|
const key = getQueryKey(pathAndInput)
|
||||||
const serverError = useState<TError | null>(`error-${key}`, () => null)
|
const serverError = useState<TError | null>(`error-${key}`, () => null)
|
||||||
const { error, data, ...rest } = await useAsyncData(
|
const { error, data, ...rest } = await useAsyncData(
|
||||||
key,
|
key,
|
||||||
() => client.query(...pathAndInput),
|
() => $client.query(...pathAndInput),
|
||||||
|
// @ts-expect-error: Internal
|
||||||
options,
|
options,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -59,3 +72,12 @@ export async function useAsyncQuery<
|
|||||||
error: serverError,
|
error: serverError,
|
||||||
} as any
|
} as any
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function useClient(): TRPCClient<AppRouter> {
|
||||||
|
const { $client } = useNuxtApp()
|
||||||
|
return $client
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useClientHeaders(initialValue: MaybeRef<Record<string, any>> = {}): Ref<Record<string, any>> {
|
||||||
|
return useStorage('trpc-nuxt-header', initialValue)
|
||||||
|
}
|
||||||
|
|||||||
30
src/runtime/plugin.ts
Normal file
30
src/runtime/plugin.ts
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
import * as trpc from '@trpc/client'
|
||||||
|
import { unref } from 'vue'
|
||||||
|
import { useClientHeaders } from './client'
|
||||||
|
import { defineNuxtPlugin, useRequestHeaders, useRuntimeConfig } from '#app'
|
||||||
|
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 client = trpc.createTRPCClient<AppRouter>({
|
||||||
|
url: `${config.baseURL}${config.endpoint}`,
|
||||||
|
headers: () => {
|
||||||
|
return {
|
||||||
|
...unref(otherHeaders),
|
||||||
|
...headers,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
nuxtApp.provide('client', client)
|
||||||
|
})
|
||||||
|
|
||||||
|
declare module '#app' {
|
||||||
|
interface NuxtApp {
|
||||||
|
$client: trpc.TRPCClient<AppRouter>
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user