import { initTRPC } from "@trpc/server"; import { TypeCompiler } from "@sinclair/typebox/compiler"; import { TRPCError } from "@trpc/server"; import type { TSchema } from "@sinclair/typebox"; /** * Initialization of tRPC backend * Should be done only once per backend! */ const t = initTRPC.create(); /** * Export reusable router and procedure helpers * that can be used throughout the router */ export const router = t.router; export const publicProcedure = t.procedure; /** * 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 RpcType(schema: T) { const check = TypeCompiler.Compile(schema); return (value: unknown) => { if (check.Check(value)) return value; const { path, message } = check.Errors(value).First(); throw new TRPCError({ message: `${message} for ${path}`, code: "BAD_REQUEST", }); }; }