mirror of
https://github.com/ArthurDanjou/trpc-nuxt.git
synced 2026-01-14 12:14:40 +01:00
85 lines
1.7 KiB
Markdown
85 lines
1.7 KiB
Markdown
---
|
|
title: Server Side Calls
|
|
---
|
|
|
|
# Server Side Calls
|
|
|
|
You may need to call your procedure(s) directly from the server, `createCaller()` function returns you an instance of `RouterCaller` able to execute queries and mutations.
|
|
|
|
## Input query example
|
|
|
|
We create the router with a input query and then we call the asynchronous `greeting` procedure to get the result.
|
|
|
|
::code-group
|
|
|
|
```ts [server/trpc/trpc.ts]
|
|
import { initTRPC } from '@trpc/server'
|
|
import { z } from 'zod'
|
|
|
|
const t = initTRPC.create()
|
|
|
|
export const router = t.router({
|
|
// Create procedure at path 'greeting'
|
|
greeting: t.procedure
|
|
.input(z.object({ name: z.string() }))
|
|
.query(({ input }) => `Hello ${input.name}`),
|
|
})
|
|
```
|
|
|
|
```ts [server/api/greeting.ts]
|
|
import { router } from '@/server/trpc/trpc'
|
|
|
|
export default eventHandler(async (event) => {
|
|
const { name } = getQuery(event)
|
|
const caller = router.createCaller({})
|
|
|
|
const greeting = await caller.greeting({ name })
|
|
|
|
return {
|
|
greeting
|
|
}
|
|
})
|
|
```
|
|
|
|
::
|
|
|
|
## Mutation example
|
|
|
|
We create the router with a mutation and then we call the asynchronous `post` procedure to get the result.
|
|
|
|
::code-group
|
|
|
|
```ts [server/trpc/trpc.ts]
|
|
import { initTRPC } from '@trpc/server'
|
|
import { z } from 'zod'
|
|
|
|
const posts = ['One', 'Two', 'Three']
|
|
|
|
const t = initTRPC.create()
|
|
export const router = t.router({
|
|
post: t.router({
|
|
add: t.procedure.input(z.string()).mutation(({ input }) => {
|
|
posts.push(input)
|
|
return posts
|
|
}),
|
|
}),
|
|
})
|
|
```
|
|
|
|
```ts [server/api/post.ts]
|
|
import { caller } from '@/server/trpc/trpc'
|
|
|
|
export default eventHandler(async (event) => {
|
|
const body = await getBody(event)
|
|
const caller = router.createCaller({})
|
|
|
|
const post = await caller.post.add(body.post)
|
|
|
|
return {
|
|
post
|
|
}
|
|
})
|
|
```
|
|
|
|
::
|