mirror of
https://github.com/ArthurDanjou/trpc-nuxt.git
synced 2026-01-14 12:14:40 +01:00
docs: add mutation example
This commit is contained in:
84
docs/content/1.get-started/3.tips/2.server-side-calls.md
Normal file
84
docs/content/1.get-started/3.tips/2.server-side-calls.md
Normal file
@@ -0,0 +1,84 @@
|
||||
---
|
||||
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.post.ts]
|
||||
import { caller } from '@/server/trpc/trpc'
|
||||
|
||||
export default eventHandler(async (event) => {
|
||||
const body = await getBody(event)
|
||||
const caller = router.createCaller({})
|
||||
|
||||
const greeting = await caller.greeting({ name: body.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()
|
||||
const router = t.router({
|
||||
post: t.router({
|
||||
add: t.procedure.input(z.string()).mutation(({ input }) => {
|
||||
posts.push(input)
|
||||
return posts
|
||||
}),
|
||||
}),
|
||||
})
|
||||
```
|
||||
|
||||
```ts [server/api/post.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
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
::
|
||||
Reference in New Issue
Block a user