mirror of
https://github.com/ArthurDanjou/trpc-nuxt.git
synced 2026-01-14 12:14:40 +01:00
Compare commits
31 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 |
15
README.md
15
README.md
@@ -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 until I found a solution https://github.com/trpc/trpc/discussions/1686
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
trpc-nuxt accepts the following options exposed under `~/server/trpc/index.ts`:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "trpc-nuxt",
|
||||
"type": "module",
|
||||
"version": "0.1.8",
|
||||
"version": "0.1.22",
|
||||
"packageManager": "pnpm@7.1.1",
|
||||
"license": "MIT",
|
||||
"main": "./dist/module.cjs",
|
||||
@@ -35,6 +35,8 @@
|
||||
"@nuxt/kit": "^3.0.0-rc.3",
|
||||
"@trpc/client": "^9.23.3",
|
||||
"@trpc/server": "^9.23.2",
|
||||
"@vueuse/core": "^8.5.0",
|
||||
"@vueuse/nuxt": "^8.5.0",
|
||||
"defu": "^6.0.0",
|
||||
"h3": "^0.7.8",
|
||||
"pathe": "^0.3.0",
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
<script setup lang="ts">
|
||||
const client = useClient()
|
||||
const headers = useClientHeaders()
|
||||
const { data: todos, pending, error, refresh } = await useAsyncQuery(['getTodos'])
|
||||
|
||||
const addHeader = () => {
|
||||
// headers.value.cookie = 'counter=69'
|
||||
console.log(headers.value)
|
||||
}
|
||||
|
||||
const addTodo = async () => {
|
||||
const title = Math.random().toString(36).slice(2, 7)
|
||||
|
||||
@@ -27,7 +33,7 @@ const addTodo = async () => {
|
||||
<div v-else-if="error?.data?.code">
|
||||
Error: {{ error.data.code }}
|
||||
</div>
|
||||
<div v-else>
|
||||
<div v-else-if="todos">
|
||||
<ul>
|
||||
<li v-for="t in todos.slice(0, 10)" :key="t.id">
|
||||
<NuxtLink :class="{ completed: t.completed }" :to="`/todo/${t.id}`">
|
||||
@@ -41,6 +47,9 @@ const addTodo = async () => {
|
||||
<button @click="() => refresh()">
|
||||
Refresh
|
||||
</button>
|
||||
<button @click="addHeader">
|
||||
Add header
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -43,7 +43,7 @@ export async function createContext(event: CompatibilityEvent) {
|
||||
|
||||
// This is just an example of something you'd might want to do in your ctx fn
|
||||
// const x = useCookies(event)
|
||||
console.log('Headers', event.req.headers)
|
||||
console.log(event.req.headers)
|
||||
|
||||
return {
|
||||
|
||||
|
||||
69
pnpm-lock.yaml
generated
69
pnpm-lock.yaml
generated
@@ -10,6 +10,8 @@ importers:
|
||||
'@nuxt/module-builder': latest
|
||||
'@trpc/client': ^9.23.3
|
||||
'@trpc/server': ^9.23.2
|
||||
'@vueuse/core': ^8.5.0
|
||||
'@vueuse/nuxt': ^8.5.0
|
||||
bumpp: ^7.1.1
|
||||
defu: ^6.0.0
|
||||
eslint: ^8.14.0
|
||||
@@ -26,6 +28,8 @@ importers:
|
||||
'@nuxt/kit': 3.0.0-rc.3
|
||||
'@trpc/client': 9.23.4_@trpc+server@9.23.4
|
||||
'@trpc/server': 9.23.4
|
||||
'@vueuse/core': 8.5.0
|
||||
'@vueuse/nuxt': 8.5.0
|
||||
defu: 6.0.0
|
||||
h3: 0.7.8
|
||||
pathe: 0.3.0
|
||||
@@ -1264,6 +1268,22 @@ packages:
|
||||
resolution: {integrity: sha512-UBc1Pg1T3yZ97vsA2ueER0F6GbJebLHYlEi4ou1H5YL4KWvMOOWwpYo9/QpWq93wxKG6Wo13IY74Hcn/f7c7Bg==}
|
||||
dev: true
|
||||
|
||||
/@vueuse/core/8.5.0:
|
||||
resolution: {integrity: sha512-VEJ6sGNsPlUp0o9BGda2YISvDZbhWJSOJu5zlp2TufRGVrLcYUKr31jyFEOj6RXzG3k/H4aCYeZyjpItfU8glw==}
|
||||
peerDependencies:
|
||||
'@vue/composition-api': ^1.1.0
|
||||
vue: ^2.6.0 || ^3.2.0
|
||||
peerDependenciesMeta:
|
||||
'@vue/composition-api':
|
||||
optional: true
|
||||
vue:
|
||||
optional: true
|
||||
dependencies:
|
||||
'@vueuse/metadata': 8.5.0
|
||||
'@vueuse/shared': 8.5.0
|
||||
vue-demi: 0.12.5
|
||||
dev: false
|
||||
|
||||
/@vueuse/head/0.7.6_vue@3.2.33:
|
||||
resolution: {integrity: sha512-cOWqCkT3WiF5oEpw+VVEWUJd9RLD5rc7DmnFp3cePsejp+t7686uKD9Z9ZU7Twb7R/BI8iexKTmXo9D/F3v6UA==}
|
||||
peerDependencies:
|
||||
@@ -1272,6 +1292,42 @@ packages:
|
||||
vue: 3.2.33
|
||||
dev: true
|
||||
|
||||
/@vueuse/metadata/8.5.0:
|
||||
resolution: {integrity: sha512-WxsD+Cd+bn+HcjpY6Dl9FJ8ywTRTT9pTwk3bCQpzEhXVYAyNczKDSahk50fCfIJKeWHhyI4B2+/ZEOxQAkUr0g==}
|
||||
dev: false
|
||||
|
||||
/@vueuse/nuxt/8.5.0:
|
||||
resolution: {integrity: sha512-riGrDwlTQbjSDxyw46oc1catXpZwzzRrEk+PTy8NQZG6uevgJ8wNuAhPVx/5oG0jYG/t2orIFfc9xGEA6uytSg==}
|
||||
dependencies:
|
||||
'@nuxt/kit': 3.0.0-rc.3
|
||||
'@vueuse/core': 8.5.0
|
||||
'@vueuse/metadata': 8.5.0
|
||||
local-pkg: 0.4.1
|
||||
vue-demi: 0.12.5
|
||||
transitivePeerDependencies:
|
||||
- '@vue/composition-api'
|
||||
- esbuild
|
||||
- rollup
|
||||
- supports-color
|
||||
- vite
|
||||
- vue
|
||||
- webpack
|
||||
dev: false
|
||||
|
||||
/@vueuse/shared/8.5.0:
|
||||
resolution: {integrity: sha512-qKG+SZb44VvGD4dU5cQ63z4JE2Yk39hQUecR0a9sEdJA01cx+XrxAvFKJfPooxwoiqalAVw/ktWK6xbyc/jS3g==}
|
||||
peerDependencies:
|
||||
'@vue/composition-api': ^1.1.0
|
||||
vue: ^2.6.0 || ^3.2.0
|
||||
peerDependenciesMeta:
|
||||
'@vue/composition-api':
|
||||
optional: true
|
||||
vue:
|
||||
optional: true
|
||||
dependencies:
|
||||
vue-demi: 0.12.5
|
||||
dev: false
|
||||
|
||||
/abbrev/1.1.1:
|
||||
resolution: {integrity: sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==}
|
||||
dev: true
|
||||
@@ -6561,6 +6617,19 @@ packages:
|
||||
bundle-runner: 0.0.1
|
||||
dev: true
|
||||
|
||||
/vue-demi/0.12.5:
|
||||
resolution: {integrity: sha512-BREuTgTYlUr0zw0EZn3hnhC3I6gPWv+Kwh4MCih6QcAeaTlaIX0DwOVN0wHej7hSvDPecz4jygy/idsgKfW58Q==}
|
||||
engines: {node: '>=12'}
|
||||
hasBin: true
|
||||
requiresBuild: true
|
||||
peerDependencies:
|
||||
'@vue/composition-api': ^1.0.0-rc.1
|
||||
vue: ^3.0.0-0 || ^2.6.0
|
||||
peerDependenciesMeta:
|
||||
'@vue/composition-api':
|
||||
optional: true
|
||||
dev: false
|
||||
|
||||
/vue-eslint-parser/8.3.0_eslint@8.15.0:
|
||||
resolution: {integrity: sha512-dzHGG3+sYwSf6zFBa0Gi9ZDshD7+ad14DGOdTLjruRVgZXe2J+DcZ9iUhyR48z5g1PqRa20yt3Njna/veLJL/g==}
|
||||
engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}
|
||||
|
||||
@@ -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
|
||||
@@ -20,11 +20,14 @@ export default defineNuxtModule<ModuleOptions>({
|
||||
},
|
||||
async setup(options, nuxt) {
|
||||
const runtimeDir = fileURLToPath(new URL('./runtime', import.meta.url))
|
||||
nuxt.options.build.transpile.push(runtimeDir, '#build/trpc-client', '#build/trpc-handler')
|
||||
nuxt.options.build.transpile.push(runtimeDir, '#build/trpc-handler')
|
||||
|
||||
const handlerPath = join(nuxt.options.buildDir, 'trpc-handler.ts')
|
||||
const trpcOptionsPath = join(nuxt.options.rootDir, 'server/trpc')
|
||||
|
||||
// Add vueuse
|
||||
nuxt.options.modules.push('@vueuse/nuxt')
|
||||
|
||||
// Final resolved configuration
|
||||
const finalConfig = nuxt.options.runtimeConfig.public.trpc = defu(nuxt.options.runtimeConfig.public.trpc, {
|
||||
baseURL: options.baseURL,
|
||||
@@ -33,8 +36,9 @@ 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') },
|
||||
{ name: 'useClientHeaders', from: join(runtimeDir, 'client') },
|
||||
)
|
||||
})
|
||||
|
||||
@@ -43,26 +47,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',
|
||||
@@ -70,14 +55,11 @@ export default defineNuxtModule<ModuleOptions>({
|
||||
getContents() {
|
||||
return `
|
||||
import { createTRPCHandler } from 'trpc-nuxt/api'
|
||||
import { useRuntimeConfig } from '#imports'
|
||||
import * as functions from '${trpcOptionsPath}'
|
||||
|
||||
const { trpc: { trpcURL } } = useRuntimeConfig().public
|
||||
|
||||
export default createTRPCHandler({
|
||||
...functions,
|
||||
trpcURL
|
||||
trpcURL: '${finalConfig.trpcURL}'
|
||||
})
|
||||
`
|
||||
},
|
||||
|
||||
@@ -6,12 +6,14 @@ import type {
|
||||
_Transform,
|
||||
} from 'nuxt/dist/app/composables/asyncData'
|
||||
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 { useAsyncData, useState } from '#app'
|
||||
// @ts-expect-error: Resolved by Nuxt
|
||||
import type { Ref } from 'vue'
|
||||
import { useAsyncData, useNuxtApp, useState } from '#app'
|
||||
import type { router } from '~/server/trpc'
|
||||
|
||||
type MaybeRef<T> = T | Ref<T>
|
||||
|
||||
type AppRouter = typeof router
|
||||
|
||||
export type inferProcedures<
|
||||
@@ -43,6 +45,7 @@ export async function useAsyncQuery<
|
||||
const { error, data, ...rest } = await useAsyncData(
|
||||
key,
|
||||
() => $client.query(...pathAndInput),
|
||||
// @ts-expect-error: Internal
|
||||
options,
|
||||
)
|
||||
|
||||
@@ -58,3 +61,12 @@ export async function useAsyncQuery<
|
||||
error: serverError,
|
||||
} 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)
|
||||
}
|
||||
|
||||
@@ -1,18 +1,30 @@
|
||||
import * as trpc from '@trpc/client'
|
||||
import { defineNuxtPlugin, useRequestHeaders } from '#app'
|
||||
import { unref } from 'vue'
|
||||
import { useClientHeaders } from './client'
|
||||
import { defineNuxtPlugin, useRequestHeaders, useRuntimeConfig } from '#app'
|
||||
import type { router } from '~/server/trpc'
|
||||
|
||||
const options = JSON.parse('<%= JSON.stringify(options) %>')
|
||||
declare type AppRouter = typeof router
|
||||
|
||||
export default defineNuxtPlugin(() => {
|
||||
const client = trpc.createTRPCClient<typeof router>({
|
||||
url: options.url as string,
|
||||
headers: useRequestHeaders(),
|
||||
export default defineNuxtPlugin((nuxtApp) => {
|
||||
const config = useRuntimeConfig().public.trpc
|
||||
const headers = useRequestHeaders()
|
||||
const otherHeaders = useClientHeaders()
|
||||
const client = trpc.createTRPCClient<AppRouter>({
|
||||
url: `${config.baseURL}${config.trpcURL}`,
|
||||
headers: () => {
|
||||
return {
|
||||
...unref(otherHeaders),
|
||||
...headers,
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
provide: {
|
||||
client,
|
||||
},
|
||||
}
|
||||
nuxtApp.provide('client', client)
|
||||
})
|
||||
|
||||
declare module '#app' {
|
||||
interface NuxtApp {
|
||||
$client: trpc.TRPCClient<AppRouter>
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user