mirror of
https://github.com/ArthurDanjou/trpc-nuxt.git
synced 2026-01-25 17:30:33 +01:00
Compare commits
29 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7f44e049c0 | ||
|
|
5a71bbf1fe | ||
|
|
285487e9bf | ||
|
|
2cfa64fcc6 | ||
|
|
eea5733dcd | ||
|
|
71bbbf2b86 | ||
|
|
2b57ab8791 | ||
|
|
f8edd769f0 | ||
|
|
419ef34de6 | ||
|
|
30c76b5859 | ||
|
|
2575beae5d | ||
|
|
b09d1af30d | ||
|
|
610e441db7 | ||
|
|
959b370729 | ||
|
|
c1c4e67694 | ||
|
|
779221d9e6 | ||
|
|
986b661e99 | ||
|
|
77325a6699 | ||
|
|
6dcb4ce8a6 | ||
|
|
c95d46f43a | ||
|
|
2844cc0bbd | ||
|
|
aeb2e1b8e3 | ||
|
|
68d9eb2461 | ||
|
|
109a07a42d | ||
|
|
7775e59b0c | ||
|
|
c23af214a3 | ||
|
|
7851846ad5 | ||
|
|
f9b0aa002e | ||
|
|
eb1bd0c700 |
@@ -143,6 +143,7 @@ export const onError = (payload: OnErrorPayload<typeof router>) => {
|
|||||||
- [Merging Routers](/recipes/merging-routers.md)
|
- [Merging Routers](/recipes/merging-routers.md)
|
||||||
- [Error Handling](/recipes/error-handling.md)
|
- [Error Handling](/recipes/error-handling.md)
|
||||||
- [Error Formatting](/recipes/error-formatting.md)
|
- [Error Formatting](/recipes/error-formatting.md)
|
||||||
|
- [Inference Helpers](/recipes/inference-helpers.md)
|
||||||
|
|
||||||
Learn more about tRPC.io [here](https://trpc.io/docs).
|
Learn more about tRPC.io [here](https://trpc.io/docs).
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "trpc-nuxt",
|
"name": "trpc-nuxt",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"version": "0.1.3",
|
"version": "0.1.16",
|
||||||
"packageManager": "pnpm@7.1.1",
|
"packageManager": "pnpm@7.1.1",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"main": "./dist/module.cjs",
|
"main": "./dist/module.cjs",
|
||||||
|
|||||||
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,12 +1,12 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
const client = useClient()
|
const { $client } = useNuxtApp()
|
||||||
const { data: todos, pending, error, refresh } = await useAsyncQuery(['getTodos'])
|
const { data: todos, pending, error, refresh } = await useAsyncQuery(['getTodos'])
|
||||||
|
|
||||||
const addTodo = async () => {
|
const addTodo = async () => {
|
||||||
const title = Math.random().toString(36).slice(2, 7)
|
const title = Math.random().toString(36).slice(2, 7)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const result = await client.mutation('addTodo', {
|
const result = await $client.mutation('addTodo', {
|
||||||
id: Date.now(),
|
id: Date.now(),
|
||||||
userId: 69,
|
userId: 69,
|
||||||
title,
|
title,
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
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'
|
||||||
|
import { useCookies } from 'h3'
|
||||||
|
|
||||||
const baseURL = 'https://jsonplaceholder.typicode.com'
|
const baseURL = 'https://jsonplaceholder.typicode.com'
|
||||||
|
|
||||||
@@ -12,7 +15,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`)
|
||||||
@@ -33,3 +36,18 @@ export const router = trpc.router()
|
|||||||
})
|
})
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
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(x)
|
||||||
|
|
||||||
|
return {
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type Context = inferAsyncReturnType<typeof createContext>
|
||||||
|
|||||||
80
recipes/inference-helpers.md
Normal file
80
recipes/inference-helpers.md
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
## Inference Helpers
|
||||||
|
|
||||||
|
`@trpc/server` exports the following helper types to assist with inferring these types from the `router` exported in `~/server/trpc/index.ts`:
|
||||||
|
|
||||||
|
- `inferProcedureOutput<TProcedure>`
|
||||||
|
- `inferProcedureInput<TProcedure>`
|
||||||
|
- `inferSubscriptionOutput<TRouter, TPath>`
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// ~/utils/trpc.ts
|
||||||
|
import type { router } from '~/server/trpc/index.ts'
|
||||||
|
|
||||||
|
type AppRouter = typeof router
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Enum containing all api query paths
|
||||||
|
*/
|
||||||
|
export type TQuery = keyof AppRouter['_def']['queries']
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Enum containing all api mutation paths
|
||||||
|
*/
|
||||||
|
export type TMutation = keyof AppRouter['_def']['mutations']
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Enum containing all api subscription paths
|
||||||
|
*/
|
||||||
|
export type TSubscription = keyof AppRouter['_def']['subscriptions']
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This is a helper method to infer the output of a query resolver
|
||||||
|
* @example type HelloOutput = InferQueryOutput<'hello'>
|
||||||
|
*/
|
||||||
|
export type InferQueryOutput<TRouteKey extends TQuery> = inferProcedureOutput<
|
||||||
|
AppRouter['_def']['queries'][TRouteKey]
|
||||||
|
>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This is a helper method to infer the input of a query resolver
|
||||||
|
* @example type HelloInput = InferQueryInput<'hello'>
|
||||||
|
*/
|
||||||
|
export type InferQueryInput<TRouteKey extends TQuery> = inferProcedureInput<
|
||||||
|
AppRouter['_def']['queries'][TRouteKey]
|
||||||
|
>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This is a helper method to infer the output of a mutation resolver
|
||||||
|
* @example type HelloOutput = InferMutationOutput<'hello'>
|
||||||
|
*/
|
||||||
|
export type InferMutationOutput<TRouteKey extends TMutation> =
|
||||||
|
inferProcedureOutput<AppRouter['_def']['mutations'][TRouteKey]>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This is a helper method to infer the input of a mutation resolver
|
||||||
|
* @example type HelloInput = InferMutationInput<'hello'>
|
||||||
|
*/
|
||||||
|
export type InferMutationInput<TRouteKey extends TMutation> =
|
||||||
|
inferProcedureInput<AppRouter['_def']['mutations'][TRouteKey]>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This is a helper method to infer the output of a subscription resolver
|
||||||
|
* @example type HelloOutput = InferSubscriptionOutput<'hello'>
|
||||||
|
*/
|
||||||
|
export type InferSubscriptionOutput<TRouteKey extends TSubscription> =
|
||||||
|
inferProcedureOutput<AppRouter['_def']['subscriptions'][TRouteKey]>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This is a helper method to infer the asynchronous output of a subscription resolver
|
||||||
|
* @example type HelloAsyncOutput = InferAsyncSubscriptionOutput<'hello'>
|
||||||
|
*/
|
||||||
|
export type InferAsyncSubscriptionOutput<TRouteKey extends TSubscription> =
|
||||||
|
inferSubscriptionOutput<AppRouter, TRouteKey>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This is a helper method to infer the input of a subscription resolver
|
||||||
|
* @example type HelloInput = InferSubscriptionInput<'hello'>
|
||||||
|
*/
|
||||||
|
export type InferSubscriptionInput<TRouteKey extends TSubscription> =
|
||||||
|
inferProcedureInput<AppRouter['_def']['subscriptions'][TRouteKey]>
|
||||||
|
```
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
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'
|
||||||
|
|
||||||
import { addServerHandler, addTemplate, defineNuxtModule } from '@nuxt/kit'
|
import { addPlugin, addServerHandler, addTemplate, defineNuxtModule } from '@nuxt/kit'
|
||||||
|
|
||||||
export interface ModuleOptions {
|
export interface ModuleOptions {
|
||||||
baseURL: string
|
baseURL: string
|
||||||
@@ -20,7 +20,7 @@ export default defineNuxtModule<ModuleOptions>({
|
|||||||
},
|
},
|
||||||
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')
|
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.rootDir, 'server/trpc')
|
||||||
@@ -33,7 +33,7 @@ export default defineNuxtModule<ModuleOptions>({
|
|||||||
|
|
||||||
nuxt.hook('autoImports:extend', (imports) => {
|
nuxt.hook('autoImports:extend', (imports) => {
|
||||||
imports.push(
|
imports.push(
|
||||||
{ name: 'useClient', from: '#build/trpc-client' },
|
{ name: 'useClient', from: join(runtimeDir, 'client') },
|
||||||
{ name: 'useAsyncQuery', from: join(runtimeDir, 'client') },
|
{ name: 'useAsyncQuery', from: join(runtimeDir, 'client') },
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
@@ -43,22 +43,7 @@ export default defineNuxtModule<ModuleOptions>({
|
|||||||
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',
|
||||||
@@ -66,14 +51,11 @@ export default defineNuxtModule<ModuleOptions>({
|
|||||||
getContents() {
|
getContents() {
|
||||||
return `
|
return `
|
||||||
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
|
trpcURL: '${finalConfig.trpcURL}'
|
||||||
})
|
})
|
||||||
`
|
`
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -6,15 +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 { useAsyncData, useNuxtApp, useState } from '#app'
|
||||||
import { useClient } from '#build/trpc-client'
|
// @ts-expect-error: Resolved by Nuxt
|
||||||
import type { router } from '~/server/trpc'
|
import type { router } from '~/server/trpc'
|
||||||
|
|
||||||
type AppRouter = typeof router
|
type AppRouter = typeof router
|
||||||
|
|
||||||
type inferProcedures<
|
export type inferProcedures<
|
||||||
TObj extends ProcedureRecord<any, any, any, any, any, any>,
|
TObj extends ProcedureRecord<any, any, any, any, any, any>,
|
||||||
> = {
|
> = {
|
||||||
[TPath in keyof TObj]: {
|
[TPath in keyof TObj]: {
|
||||||
@@ -23,10 +23,10 @@ type inferProcedures<
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
type TQueries = AppRouter['_def']['queries']
|
export type TQueries = AppRouter['_def']['queries']
|
||||||
type TError = TRPCClientErrorLike<AppRouter>
|
export type TError = TRPCClientErrorLike<AppRouter>
|
||||||
|
|
||||||
type TQueryValues = inferProcedures<AppRouter['_def']['queries']>
|
export type TQueryValues = inferProcedures<AppRouter['_def']['queries']>
|
||||||
|
|
||||||
export async function useAsyncQuery<
|
export async function useAsyncQuery<
|
||||||
TPath extends keyof TQueryValues & string,
|
TPath extends keyof TQueryValues & string,
|
||||||
@@ -37,12 +37,12 @@ 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 = `${pathAndInput[0]}-${objectHash(pathAndInput[1] ? JSON.stringify(pathAndInput[1]) : '')}`
|
||||||
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),
|
||||||
options,
|
options,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -58,3 +58,8 @@ export async function useAsyncQuery<
|
|||||||
error: serverError,
|
error: serverError,
|
||||||
} as any
|
} as any
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function useClient(): TRPCClient<AppRouter> {
|
||||||
|
const { $client } = useNuxtApp()
|
||||||
|
return $client
|
||||||
|
}
|
||||||
|
|||||||
26
src/runtime/plugin.ts
Normal file
26
src/runtime/plugin.ts
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import * as trpc from '@trpc/client'
|
||||||
|
// @ts-expect-error: Resolved by Nuxt
|
||||||
|
import { defineNuxtPlugin, useRequestHeaders, useRuntimeConfig } from '#app'
|
||||||
|
import type { router } from '~/server/trpc'
|
||||||
|
|
||||||
|
declare type AppRouter = typeof router
|
||||||
|
|
||||||
|
export default defineNuxtPlugin(() => {
|
||||||
|
const config = useRuntimeConfig().public.trpc
|
||||||
|
const client = trpc.createTRPCClient<AppRouter>({
|
||||||
|
url: `${config.baseURL}${config.trpcURL}`,
|
||||||
|
headers: useRequestHeaders(),
|
||||||
|
})
|
||||||
|
|
||||||
|
return {
|
||||||
|
provide: {
|
||||||
|
client,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
declare module '#app' {
|
||||||
|
interface NuxtApp {
|
||||||
|
$client: trpc.TRPCClient<AppRouter>
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user