### Development Setup and Testing Commands Source: https://github.com/omar-dulaimi/prisma-trpc-generator/blob/master/README.md This section outlines the commands for setting up the development environment, including installing dependencies, building the project, and running tests. It also specifies commands for running specific test suites. ```bash git clone https://github.com/your-username/prisma-trpc-generator.git cd prisma-trpc-generator npm install npm run generate npm test npm run lint npm run format npm run test:integration npm run test:coverage npm run test:comprehensive ``` -------------------------------- ### Prisma tRPC Generator Configuration Example Source: https://github.com/omar-dulaimi/prisma-trpc-generator/blob/master/README.md An example JSON configuration file for prisma-trpc-generator, enabling features like Zod validation, middleware, and OpenAPI generation. ```json { "withZod": true, "withMiddleware": true, "withShield": "./shield", "contextPath": "./context", "trpcOptionsPath": "./trpcOptions", "dateTimeStrategy": "date", "withMeta": false, "postman": true, "postmanExamples": "skeleton", "openapi": true, "withRequestId": false, "withLogging": false, "withServices": false } ``` -------------------------------- ### Install Prisma tRPC Generator (npm, yarn, pnpm) Source: https://github.com/omar-dulaimi/prisma-trpc-generator/blob/master/README.md Installs the prisma-trpc-generator package using npm, yarn, or pnpm. ```bash # npm npm install prisma-trpc-generator # yarn yarn add prisma-trpc-generator # pnpm pnpm add prisma-trpc-generator ``` -------------------------------- ### Building and Testing Commands Source: https://github.com/omar-dulaimi/prisma-trpc-generator/blob/master/CLAUDE.md Commands for compiling TypeScript, running Prisma generate for testing the generator itself, and testing the generator against an example schema. ```bash npm run generate tsc npx prisma generate ``` -------------------------------- ### Client-side tRPC Usage with React Query Source: https://github.com/omar-dulaimi/prisma-trpc-generator/blob/master/README.md This example shows how to use tRPC on the client-side with React Query for data fetching and mutations. It initializes the tRPC client and demonstrates querying a list of posts and creating a new post. ```typescript import { createTRPCReact } from '@trpc/react-query'; import type { AppRouter } from '@/server/api/root'; export const trpc = createTRPCReact(); const PostList = () => { const { data: posts, isLoading } = trpc.post.findMany.useQuery(); const createPost = trpc.post.createOne.useMutation(); if (isLoading) return
Loading...
; return (
{posts?.map((post) => (
{post.title}
))}
); }; ``` -------------------------------- ### Basic CRUD with Authentication (tRPC) Source: https://github.com/omar-dulaimi/prisma-trpc-generator/blob/master/README.md Provides an example of a tRPC router for 'Post' operations, including fetching all published posts, creating a new post, and updating a post. It uses protected procedures to enforce authentication and associates posts with the logged-in user. ```typescript // src/server/routers/posts.ts import { z } from 'zod'; import { createTRPCRouter, protectedProcedure, publicProcedure } from '../trpc'; export const postsRouter = createTRPCRouter({ getAll: publicProcedure.query(({ ctx }) => ctx.prisma.post.findMany({ where: { published: true }, include: { author: { select: { name: true } } }, }), ), create: protectedProcedure .input( z.object({ title: z.string().min(1), content: z.string().optional() }), ) .mutation(({ ctx, input }) => ctx.prisma.post.create({ data: { ...input, authorId: ctx.user.id } }), ), update: protectedProcedure .input( z.object({ id: z.number(), title: z.string().min(1).optional(), content: z.string().optional(), }), ) .mutation(async ({ ctx, input }) => { const { id, ...data } = input; const post = await ctx.prisma.post.findFirst({ where: { id, authorId: ctx.user.id }, }); if (!post) throw new TRPCError({ code: 'FORBIDDEN' }); return ctx.prisma.post.update({ where: { id }, data }); }), }); ``` -------------------------------- ### Publishing Commands Source: https://github.com/omar-dulaimi/prisma-trpc-generator/blob/master/CLAUDE.md Commands for building and publishing the package, including a build script for compilation, packaging, and preparation for publishing. ```bash npm run package:publish ./package.sh ``` -------------------------------- ### Migration from Inline Configuration Source: https://github.com/omar-dulaimi/prisma-trpc-generator/blob/master/README.md Provides steps to migrate existing inline TRPC generator configurations to a dedicated `prisma/trpc.config.json` file. ```APIDOC ## Migration from Inline Configuration ### Description This section details the process for migrating from inline configuration options within the `generator trpc` block to a separate `prisma/trpc.config.json` file. ### Migration Steps: 1. **Create Configuration File**: Create a new file named `prisma/trpc.config.json`. 2. **Move Inline Keys**: Transfer all existing inline configuration keys (e.g., `withMiddleware`, `auth`, `openapi`) from your `schema.prisma` file into the `prisma/trpc.config.json` file. 3. **Update Generator Block**: Modify your `schema.prisma` file's `generator trpc` block to only include the `output` directive and the `config` directive pointing to the new JSON file: ```prisma generator trpc { provider = "prisma-trpc-generator" output = "./src/trpc" config = "prisma/trpc.config.json" } ``` 4. **Run Generation**: Execute the Prisma generation command (e.g., `npx prisma generate`). **Note**: If you still have inline keys in your `schema.prisma` file after performing these steps, the generator will ignore them and issue a warning. ``` -------------------------------- ### Configuration Schema and Defaults Source: https://github.com/omar-dulaimi/prisma-trpc-generator/blob/master/CLAUDE.md Zod schema for validating generator options, supporting options like withZod, withMiddleware, withShield, contextPath, etc. Default paths are relative to generated files. ```typescript import { z } from 'zod'; export const ConfigSchema = z.object({ output: z.string().default('../../../src/'), withZod: z.boolean().default(true), withMiddleware: z.boolean().default(true), withShield: z.boolean().default(false), contextPath: z.string().optional(), prismaContextPath: z.string().optional(), generateModelActions: z.record(z.string(), z.boolean()).optional(), }); export type Config = z.infer; export function parseConfig(config: Record): Config { const parsed = ConfigSchema.safeParse(config); if (!parsed.success) { throw new Error(`Invalid generator configuration: ${parsed.error.errors.map(e => e.message).join(', ')}`); } return parsed.data; } ``` -------------------------------- ### TRPC Generator Configuration Options Source: https://github.com/omar-dulaimi/prisma-trpc-generator/blob/master/README.md Details various configuration keys for the `prisma-trpc-generator`, including options for middleware, authentication, request IDs, metadata, OpenAPI, Postman, and DDD services. ```APIDOC ## TRPC Generator Configuration Options ### Description This section outlines the available configuration options that can be passed to the `prisma-trpc-generator` to customize its output and behavior. ### 1. Middleware & Shield - **Key**: `withMiddleware` (boolean | string), `withShield` (boolean | string) - **Usage**: - `withMiddleware: true`: Includes a basic middleware scaffold. Set to a string path to use a custom middleware file. - `withShield: true`: Imports `permissions` and exposes `shieldedProcedure` in `createRouter.ts`. ### 2. Authentication (session / JWT / custom) - **Key**: `auth` (boolean | object) - **Usage**: - `auth: true`: Enables authentication scaffolding. - `auth: { strategy?: 'session'|'jwt'|'custom'; rolesField?: string; ... }`: Configures the authentication strategy (e.g., JWT, session, custom) and related options. - **Generated Files**: `routers/helpers/auth-strategy.ts`, `routers/helpers/auth.ts`, `createRouter.ts` with `authMiddleware`, `protectedProcedure`, `roleProcedure`. - **See Also**: `docs/usage/auth.md` for detailed strategy hooks and examples. ### 3. Request ID + Logging - **Keys**: `withRequestId` (boolean), `withLogging` (boolean) - **Usage**: - `withRequestId: true`: Adds `requestId` middleware. - `withLogging: true`: Includes optional structured logging around procedures. - **Note**: To propagate `requestId` into errors, configure `trpcOptions.errorFormatter`. ### 4. tRPC Metadata Support - **Key**: `withMeta` (boolean | object) - **Usage**: - `withMeta: true`: Adds `.meta()` calls to generated procedures. - `withMeta: { openapi?: boolean; auth?: boolean; description?: boolean; defaultMeta?: object }`: Configures metadata generation for OpenAPI, authentication, descriptions, and default metadata. ### 5. OpenAPI (MVP) - **Key**: `openapi` (boolean | object) - **Usage**: - `openapi: true`: Emits `openapi/openapi.json` and `routers/adapters/openapi.ts`. - `openapi: { enabled?: boolean; title?: string; version?: string; baseUrl?: string; pathPrefix?: string; pathStyle?: 'slash'|'dot'; includeExamples?: boolean }`: Configures OpenAPI generation details. - **Note**: Paths map to tRPC endpoints (POST) with `{ input: {} }` request body schemas. ### 6. Postman Collection - **Key**: `postman` (boolean | object) - **Usage**: - `postman: true`: Emits `postman/collection.json`. - `postman: { endpoint?: string; envName?: string; fromOpenApi?: boolean; examples?: 'none'|'skeleton' }`: Configures Postman collection generation, including derivation from OpenAPI and example inclusion. ### 7. DDD Services (Optional) - **Keys**: `withServices`, `serviceStyle`, `serviceDir`, `withListMethod`, `serviceImports` - **Usage**: Enables generation of BaseService and per-model service stubs, allowing routers to delegate logic to services. - **Features**: Includes tenancy/soft-delete helpers in the service layer. ``` -------------------------------- ### tRPC Shield Integration for Permissions (TypeScript) Source: https://github.com/omar-dulaimi/prisma-trpc-generator/blob/master/README.md Shows how to integrate tRPC Shield for access control, defining rules for authentication and ownership. This allows fine-grained permissions for different tRPC procedures. ```typescript // src/permissions.ts import { shield, rule, and } from 'trpc-shield'; const isAuthenticated = rule()(async (_parent, _args, ctx) => !!ctx.user); const isOwner = rule()(async (_parent, args, ctx) => { if (!args.where?.id) return false; const post = await ctx.prisma.post.findUnique({ where: { id: args.where.id }, select: { authorId: true }, }); return post?.authorId === ctx.user?.id; }); export const permissions = shield({ query: { findManyPost: true, // Public findUniqueUser: isAuthenticated, }, mutation: { createOnePost: isAuthenticated, updateOnePost: and(isAuthenticated, isOwner), deleteOnePost: and(isAuthenticated, isOwner), }, }); ``` -------------------------------- ### Generated tRPC Routers Structure Source: https://github.com/omar-dulaimi/prisma-trpc-generator/blob/master/README.md Illustrates the directory structure of generated tRPC routers and schemas based on a Prisma schema. It shows the organization of main app routers, helper routers, model-specific routers, and Zod validation schemas. ```text generated/ ├── routers/ │ ├── index.ts # Main app router combining all model routers │ ├── helpers/ │ │ └── createRouter.ts # Base router factory with middleware/shield setup │ ├── User.router.ts # User CRUD operations │ └── Post.router.ts # Post CRUD operations └── schemas/ # Zod validation schemas (if withZod: true) ├── objects/ ├── findManyUser.schema.ts ├── createOneUser.schema.ts └── index.ts # Barrel exports ``` -------------------------------- ### Custom tRPC Context with Prisma and User Info (TypeScript) Source: https://github.com/omar-dulaimi/prisma-trpc-generator/blob/master/README.md Defines a custom tRPC context interface that includes Prisma client and user information, and provides a factory function to create this context from a request. ```typescript // src/context.ts import { PrismaClient } from '@prisma/client'; const prisma = new PrismaClient(); export interface Context { prisma: PrismaClient; user?: { id: string; email: string; role: string }; } export const createContext = async ({ req }): Promise => { const user = await getUserFromRequest(req); return { prisma, user }; }; ``` -------------------------------- ### Next.js App Router Integration with tRPC Source: https://github.com/omar-dulaimi/prisma-trpc-generator/blob/master/README.md This snippet demonstrates how to set up a tRPC request handler for Next.js App Router. It utilizes `@trpc/server/adapters/fetch` to handle requests, requiring the tRPC router and a context creation function. ```typescript import { fetchRequestHandler } from '@trpc/server/adapters/fetch'; import { appRouter } from '@/server/api/root'; import { createContext } from '@/server/api/context'; const handler = (req: Request) => fetchRequestHandler({ endpoint: '/api/trpc', req, router: appRouter, createContext, }); export { handler as GET, handler as POST }; ``` -------------------------------- ### Custom tRPC Middleware (TypeScript) Source: https://github.com/omar-dulaimi/prisma-trpc-generator/blob/master/README.md Demonstrates how to create custom middleware for tRPC, including authentication and logging. These middlewares can be applied to protect routes or add cross-cutting concerns. ```typescript // src/middleware.ts import { TRPCError } from '@trpc/server'; import { t } from './trpc'; export const authMiddleware = t.middleware(async ({ ctx, next }) => { if (!ctx.user) { throw new TRPCError({ code: 'UNAUTHORIZED' }); } return next({ ctx: { ...ctx, user: ctx.user, }, }); }); export const loggingMiddleware = t.middleware(async ({ path, type, next }) => { console.log(`tRPC ${type} ${path}`); return next(); }); ``` -------------------------------- ### Add Prisma Generator to Schema Source: https://github.com/omar-dulaimi/prisma-trpc-generator/blob/master/README.md Configures the Prisma schema to use the custom tRPC generator. It specifies the provider, output directory, and the path to the configuration file. ```prisma generator trpc { provider = "node ./lib/generator.js" output = "./prisma/generated" config = "./prisma/trpc.config.json" } ``` -------------------------------- ### Generated Output Structure Source: https://github.com/omar-dulaimi/prisma-trpc-generator/blob/master/CLAUDE.md The expected file structure of the generated output, including routers, helper files, and schemas. ```tree generated/ ├── routers/ │ ├── index.ts # Main app router that combines all model routers │ ├── helpers/ │ │ └── createRouter.ts # Base router factory with middleware/shield setup │ └── [Model].router.ts # Individual model routers (User.router.ts, Post.router.ts, etc.) └── schemas/ # Zod validation schemas (if withZod: true) ``` -------------------------------- ### Generate tRPC Routers Source: https://github.com/omar-dulaimi/prisma-trpc-generator/blob/master/README.md Executes the Prisma generate command to create tRPC routers based on the schema and configuration. Requires 'strict': true in tsconfig.json. ```bash npx prisma generate ``` -------------------------------- ### Extending Zod Schemas with Prisma Comments Source: https://github.com/omar-dulaimi/prisma-trpc-generator/blob/master/README.md Demonstrates how to add Zod validation constraints directly within Prisma schema comments, which are then used by the generator to create Zod schemas for input validation. ```APIDOC ## Prisma Schema Extensions with Zod Comments ### Description This section explains how to embed Zod validation rules within Prisma schema comments. The `prisma-trpc-generator` parses these comments to automatically generate Zod schemas with the specified validations for your TRPC procedures. ### Example Prisma Schema ```prisma model User { id Int @id @default(autoincrement()) /// @zod.number.int() email String @unique /// @zod.string.email() name String? /// @zod.string.min(1).max(100) age Int? /// @zod.number.int().min(0).max(120) posts Post[] } model Post { id Int @id @default(autoincrement()) /// @zod.number.int() title String /// @zod.string.min(1).max(255, { message: "Title must be shorter than 256 characters" }) content String? /// @zod.string.max(10000) published Boolean @default(false) author User? @relation(fields: [authorId], references: [id]) authorId Int? } ``` ### Generated Zod Schema Example ```typescript import { z } from 'zod'; export const UserCreateInput = z.object({ id: z.number().int(), email: z.string().email(), name: z.string().min(1).max(100).nullish(), age: z.number().int().min(0).max(120).nullish(), // ... other fields }); // For more advanced Zod validation options, refer to the official prisma-zod-generator documentation. ``` ### Resource - [Prisma Zod Generator Documentation](https://github.com/omar-dulaimi/prisma-zod-generator) ``` -------------------------------- ### Configure JWT Authentication Source: https://github.com/omar-dulaimi/prisma-trpc-generator/blob/master/docs/usage/auth.md Configures JSON Web Token (JWT) authentication. This includes specifying the JWT header, scheme, secret environment variable, and paths for token verification and user retrieval from the payload. Defaults to HS256. ```json { "auth": { "strategy": "jwt", "jwt": { "header": "authorization", "scheme": "Bearer", "secretEnv": "JWT_SECRET", "verifyPath": "../../src/auth/verifyToken", "getUserFromPayloadPath": "../../src/auth/getUserFromPayload" } } } ``` -------------------------------- ### Prisma Generator Logic Source: https://github.com/omar-dulaimi/prisma-trpc-generator/blob/master/CLAUDE.md The main generator function that processes the Prisma schema and generates tRPC routers. It integrates with prisma-zod-generator and prisma-trpc-shield-generator and creates router files in the specified output directory. ```typescript import { generatorHandler } from '@prisma/generator-helper'; import { logger } from '@prisma/sdk'; import path from 'path'; import { generateRouters } from './helpers'; import { Config, parseConfig } from './config'; generatorHandler({ async onGenerate(options) { logger.info('Starting Prisma TRPC Generator...'); const config: Config = parseConfig(options.generator.config); const outputDir = path.resolve(options.dirname, config.output); try { await generateRouters(options.dmmf, config, outputDir); logger.success('Prisma TRPC routers generated successfully!'); } catch (error) { logger.error('Error generating Prisma TRPC routers:', error); throw error; } }, }); ``` -------------------------------- ### Configure Session Authentication Source: https://github.com/omar-dulaimi/prisma-trpc-generator/blob/master/docs/usage/auth.md Enables session-based authentication by specifying the path to a module that exports a `getUser` function. This function is responsible for retrieving user information from the incoming request. ```json { "auth": { "strategy": "session", "session": { "getUserPath": "../../src/auth/getUser" } } } ``` -------------------------------- ### Configure Custom Authentication Source: https://github.com/omar-dulaimi/prisma-trpc-generator/blob/master/docs/usage/auth.md Enables custom authentication by providing the path to a module that exports a `resolveUser` function. This function handles the custom logic for authenticating requests and resolving the user. ```json { "auth": { "strategy": "custom", "custom": { "resolverPath": "../../src/auth/resolveUser" } } } ``` -------------------------------- ### Custom tRPC Options with SuperJSON and ZodError Formatting (TypeScript) Source: https://github.com/omar-dulaimi/prisma-trpc-generator/blob/master/README.md Configures custom tRPC options, including using SuperJSON for data serialization and providing a custom error formatter to include Zod validation errors. ```typescript // src/trpcOptions.ts import { ZodError } from 'zod'; import superjson from 'superjson'; export default { transformer: superjson, errorFormatter({ shape, error }) { return { ...shape, data: { ...shape.data, zodError: error.code === 'BAD_REQUEST' && error.cause instanceof ZodError ? error.cause.flatten() : null, }, }; }, }; ``` -------------------------------- ### Extend Zod Schemas with Prisma Comments Source: https://github.com/omar-dulaimi/prisma-trpc-generator/blob/master/README.md Add Zod validation constraints directly within Prisma schema comments. These comments are parsed by the generator to produce Zod schemas with the specified validations for models like User and Post. ```prisma model User { id Int @id @default(autoincrement()) /// @zod.number.int() email String @unique /// @zod.string.email() name String? /// @zod.string.min(1).max(100) age Int? /// @zod.number.int().min(0).max(120) posts Post[] } model Post { id Int @id @default(autoincrement()) /// @zod.number.int() title String /// @zod.string.min(1).max(255, { message: "Title must be shorter than 256 characters" }) content String? /// @zod.string.max(10000) published Boolean @default(false) author User? @relation(fields: [authorId], references: [id]) authorId Int? } ``` ```typescript export const UserCreateInput = z.object({ id: z.number().int(), email: z.string().email(), name: z.string().min(1).max(100).nullish(), age: z.number().int().min(0).max(120).nullish(), // ... }); ``` -------------------------------- ### Skipping Models in Generation (Prisma) Source: https://github.com/omar-dulaimi/prisma-trpc-generator/blob/master/README.md Demonstrates how to prevent a model from being generated by the tRPC generator by adding a specific annotation to the Prisma schema. ```prisma /// @@Gen.model(hide: true) model InternalLog { id Int @id @default(autoincrement()) message String createdAt DateTime @default(now()) } ``` -------------------------------- ### Configure Role Field for Auth Source: https://github.com/omar-dulaimi/prisma-trpc-generator/blob/master/docs/usage/auth.md Sets the user field name used for role-based access control checks. By default, it is set to 'role'. This allows customization of how user roles are identified. ```json { "auth": { "rolesField": "roles" } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.