mirror of
https://github.com/ArthurDanjou/trpc-nuxt.git
synced 2026-01-14 12:14:40 +01:00
add onError handler
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
const client = useClient()
|
||||
const data = await client.query('getUser', {
|
||||
name: 'roberts',
|
||||
const { data, error } = await useAsyncData('random', () => client.query('hello'), {
|
||||
server: false,
|
||||
})
|
||||
</script>
|
||||
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
import * as trpc from '@trpc/server'
|
||||
import { z } from 'zod'
|
||||
import type { CompatibilityEvent } from 'h3'
|
||||
|
||||
export const router = trpc
|
||||
.router()
|
||||
.query('getUser', {
|
||||
input: z.object({ name: z.string().min(5) }),
|
||||
async resolve(req) {
|
||||
return { id: 1, name: req.input.name }
|
||||
},
|
||||
})
|
||||
.query('hello', {
|
||||
resolve: () => 'world',
|
||||
})
|
||||
|
||||
// optional
|
||||
export const createContext = (event: CompatibilityEvent) => {
|
||||
return {
|
||||
user: {
|
||||
id: 69,
|
||||
name: 'robert',
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// optional
|
||||
export const responseMeta = () => {
|
||||
// ...
|
||||
return {
|
||||
// { headers: ... }
|
||||
}
|
||||
}
|
||||
|
||||
export type Router = typeof router
|
||||
@@ -11,6 +11,7 @@ import { createURL } from 'ufo'
|
||||
import type { CompatibilityEvent } from 'h3'
|
||||
import { defineEventHandler, isMethod, useBody } from 'h3'
|
||||
import type { TRPCResponse } from '@trpc/server/dist/declarations/src/rpc'
|
||||
import type { OnErrorFunction } from '@trpc/server/dist/declarations/src/internals/OnErrorFunction'
|
||||
|
||||
type MaybePromise<T> = T | Promise<T>
|
||||
|
||||
@@ -28,17 +29,18 @@ export function createTRPCHandler<Router extends AnyRouter>({
|
||||
router,
|
||||
createContext,
|
||||
responseMeta,
|
||||
onError,
|
||||
}: {
|
||||
router: Router
|
||||
createContext?: CreateContextFn<Router>
|
||||
responseMeta?: ResponseMetaFn<Router>
|
||||
onError?: OnErrorFunction<Router, CompatibilityEvent['req']>
|
||||
}) {
|
||||
const url = '/trpc'
|
||||
|
||||
return defineEventHandler(async (event) => {
|
||||
const {
|
||||
req,
|
||||
res,
|
||||
context,
|
||||
} = event
|
||||
|
||||
const $url = createURL(req.url)
|
||||
@@ -51,9 +53,15 @@ export function createTRPCHandler<Router extends AnyRouter>({
|
||||
body: isMethod(event, 'GET') ? null : await useBody(event),
|
||||
query: $url.searchParams,
|
||||
},
|
||||
path: $url.pathname.substring(url.length + 1),
|
||||
path: context.params.path,
|
||||
createContext: async () => createContext?.(event),
|
||||
responseMeta,
|
||||
onError: (o) => {
|
||||
onError?.({
|
||||
...o,
|
||||
req,
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
const { status, headers, body } = httpResponse
|
||||
|
||||
Reference in New Issue
Block a user