basic route-specific trpc file example

This commit is contained in:
Avraham Sakal
2025-06-29 15:17:10 -04:00
parent 602ba72f75
commit 5ef118e9bc
10 changed files with 303 additions and 44 deletions
+1 -1
View File
@@ -1,5 +1,5 @@
import { createTRPCProxyClient, httpBatchLink } from "@trpc/client";
import type { AppRouter } from "./server.js";
import type { AppRouter } from "./router.js";
export const trpc = createTRPCProxyClient<AppRouter>({
links: [
+23
View File
@@ -0,0 +1,23 @@
import { router, publicProcedure } from "../trpc/server";
import { todos } from "../database/todoItems";
import { chat } from "../pages/chat/trpc";
export const appRouter = router({
demo: publicProcedure.query(async () => {
return { demo: true };
}),
onNewTodo: publicProcedure
.input((value): string => {
if (typeof value === "string") {
return value;
}
throw new Error("Input is not a string");
})
.mutation(async (opts) => {
console.log("Received new todo", { text: opts.input });
todos.push({ text: opts.input });
}),
chat,
});
export type AppRouter = typeof appRouter;
+20 -20
View File
@@ -1,5 +1,6 @@
import { initTRPC } from "@trpc/server";
import { todos } from "../database/todoItems";
import type { TSchema } from "@sinclair/typebox";
import { TypeCompiler } from "@sinclair/typebox/compiler";
import { initTRPC, TRPCError } from "@trpc/server";
/**
* Initialization of tRPC backend
@@ -14,21 +15,20 @@ const t = initTRPC.context<object>().create();
export const router = t.router;
export const publicProcedure = t.procedure;
export const appRouter = router({
demo: publicProcedure.query(async () => {
return { demo: true };
}),
onNewTodo: publicProcedure
.input((value): string => {
if (typeof value === "string") {
return value;
}
throw new Error("Input is not a string");
})
.mutation(async (opts) => {
console.log("Received new todo", { text: opts.input });
todos.push({ text: opts.input });
}),
});
export type AppRouter = typeof appRouter;
/**
* Generate a TRPC-compatible validator function given a Typebox schema.
* This was copied from [https://github.com/sinclairzx81/typebox/blob/6cfcdc02cc813af2f1be57407c771fc4fadfc34a/example/trpc/readme.md].
* @param schema A Typebox schema
* @returns A TRPC-compatible validator function
*/
export function Validator<T extends TSchema>(schema: T) {
const check = TypeCompiler.Compile(schema);
return (value: unknown) => {
if (check.Check(value)) return value;
const err = check.Errors(value).First();
throw new TRPCError({
message: `${err?.message} for ${err?.path}`,
code: "BAD_REQUEST",
});
};
}