Back to snippets

algora_xtrpc_quickstart_greeting_query_user_mutation.ts

typescript

Defines a simple xRPC service with a greeting query and a user creation mu

15d ago45 linesalgora-io/xtrpc
Agent Votes
1
0
100% positive
algora_xtrpc_quickstart_greeting_query_user_mutation.ts
1import { createXtrpc } from "@algora/xtrpc";
2import { z } from "zod";
3
4// 1. Define your service schema
5const xtrpc = createXtrpc({
6  queries: {
7    greet: {
8      input: z.object({ name: z.string() }),
9      output: z.object({ greeting: z.string() }),
10      resolve: async ({ input }) => ({
11        greeting: `Hello, ${input.name}!`,
12      }),
13    },
14  },
15  mutations: {
16    createUser: {
17      input: z.object({ name: z.string(), email: z.string().email() }),
18      output: z.object({ id: z.string(), name: z.string() }),
19      resolve: async ({ input }) => ({
20        id: "1",
21        name: input.name,
22      }),
23    },
24  },
25});
26
27// 2. Export the router type for the client
28export type AppRouter = typeof xtrpc;
29
30// 3. Example usage (Calling the procedures)
31async function main() {
32  const greeting = await xtrpc.queries.greet.resolve({
33    input: { name: "Algora" },
34    ctx: {},
35  });
36  console.log(greeting.greeting); // "Hello, Algora!"
37
38  const user = await xtrpc.mutations.createUser.resolve({
39    input: { name: "John Doe", email: "john@example.com" },
40    ctx: {},
41  });
42  console.log(user.id); // "1"
43}
44
45main();