Experiments with tRPC and Nuxt Server API
This commit is contained in:
15
server/api/test/[hello].ts
Normal file
15
server/api/test/[hello].ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
const pathSchema = z.object({
|
||||
hello: z.string()
|
||||
});
|
||||
|
||||
const bodySchema = z.object({
|
||||
world: z.string()
|
||||
});
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const pathParams = await getValidatedRouterParams(event, pathSchema.parse);
|
||||
const body = await readValidatedBody(event, bodySchema.parse);
|
||||
return { risultato: `${pathParams.hello}-${body.world}` };
|
||||
});
|
||||
7
server/api/trpc/[trpc].ts
Normal file
7
server/api/trpc/[trpc].ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { createTRPCNuxtHandler } from 'trpc-nuxt/server';
|
||||
import { appRouter } from '~/server/trpc/routers';
|
||||
|
||||
export default createTRPCNuxtHandler({
|
||||
endpoint: '/api/trpc',
|
||||
router: appRouter,
|
||||
});
|
||||
9
server/trpc/init.ts
Normal file
9
server/trpc/init.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { initTRPC } from '@trpc/server';
|
||||
|
||||
// You can use any variable name you like.
|
||||
// We use t to keep things simple.
|
||||
const t = initTRPC.create();
|
||||
|
||||
export const router = t.router; // createTRPCRouter
|
||||
export const createCallerFactory = t.createCallerFactory;
|
||||
export const publicProcedure = t.procedure; // baseProcedure
|
||||
19
server/trpc/routers/index.ts
Normal file
19
server/trpc/routers/index.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { publicProcedure, router } from '~/server/trpc/init';
|
||||
import { z } from 'zod';
|
||||
|
||||
export const appRouter = router({
|
||||
hello: publicProcedure
|
||||
.input(
|
||||
z.object({
|
||||
text: z.string(),
|
||||
}),
|
||||
)
|
||||
.query((opts) => {
|
||||
return {
|
||||
greeting: `hello ${opts.input.text}`,
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
// export type definition of API
|
||||
export type AppRouter = typeof appRouter;
|
||||
Reference in New Issue
Block a user