mirror of
https://github.com/ArthurDanjou/trpc-nuxt.git
synced 2026-01-23 16:30:41 +01:00
84 lines
2.0 KiB
Markdown
84 lines
2.0 KiB
Markdown
---
|
|
title: Server
|
|
description: '@nuxtjs/supabase is a Nuxt module for first class integration with Supabase.'
|
|
---
|
|
|
|
# Server
|
|
|
|
## Recommended file structure
|
|
|
|
Recommended but not enforced file structure. This is what you get when starting from [the examples](../main/example-apps.md).
|
|
|
|
```graphql
|
|
.
|
|
├── server
|
|
│ ├── api
|
|
│ │ └── trpc
|
|
│ │ └── [trpc].ts # <-- tRPC HTTP handler
|
|
│ │ └── [..]
|
|
│ ├── trpc
|
|
│ │ ├── routers
|
|
│ │ │ ├── index.ts # <-- main app router
|
|
│ │ │ ├── todo.ts # <-- sub routers
|
|
│ │ │ └── [..]
|
|
│ │ ├── context.ts # <-- create app context
|
|
│ │ └── trpc.ts # <-- procedure helpers
|
|
├── plugins
|
|
│ ├── client.ts # <-- tRPC Client as a plugin
|
|
└── [..]
|
|
```
|
|
|
|
## 1. Create a tRPC router
|
|
|
|
Initialize your tRPC backend using the `initTRPC` function and create your first router.
|
|
|
|
::code-group
|
|
|
|
```ts [server/trpc/index.ts]
|
|
import { TRPCError, initTRPC } from '@trpc/server'
|
|
|
|
// Avoid exporting the entire t-object since it's not very
|
|
// descriptive and can be confusing to newcomers used to t
|
|
// meaning translation in i18n libraries.
|
|
const t = initTRPC.create()
|
|
|
|
// Base router and procedure helpers
|
|
export const router = t.router
|
|
export const publicProcedure = t.procedure
|
|
```
|
|
|
|
```ts [server/trpc/routers/index.ts]
|
|
import { z } from 'zod'
|
|
import { publicProcedure, router } from '..'
|
|
|
|
export const appRouter = router({
|
|
hello: publicProcedure
|
|
.input(
|
|
z.object({
|
|
text: z.string().nullish(),
|
|
}),
|
|
)
|
|
.query(({ input }) => {
|
|
return {
|
|
greeting: `hello ${input?.text ?? 'world'}`,
|
|
}
|
|
}),
|
|
})
|
|
|
|
// export type definition of API
|
|
export type AppRouter = typeof appRouter
|
|
```
|
|
|
|
```ts [server/api/trpc/[trpc].ts]
|
|
import { createNuxtApiHandler } from 'trpc-nuxt'
|
|
import { appRouter } from '../../trpc/routers'
|
|
|
|
// export API handler
|
|
export default createNuxtApiHandler({
|
|
router: appRouter,
|
|
createContext: () => ({}),
|
|
})
|
|
```
|
|
|
|
::
|