basic route-specific trpc file example
This commit is contained in:
+1
-1
@@ -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: [
|
||||
|
||||
@@ -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
@@ -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",
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user