pothos-prisma-generator
v1.4.0
Published
Automatic generation of GraphQL schema from prisma schema.
Readme
pothos-prisma-generator
Automatic generation of GraphQL schema from Prisma schema for Pothos GraphQL.

Overview
pothos-prisma-generator automatically generates full-featured GraphQL queries, mutations, relation fields, and filters directly from your schema.prisma.
The schema is built dynamically in-memory at runtime—no need to generate and manage boilerplate resolver/type files.
Supported Operations & Features
- Queries:
count<Model>,findUnique<Model>,findFirst<Model>,findMany<Model> - Mutations:
createOne<Model>,createMany<Model>,updateOne<Model>,updateMany<Model>,deleteOne<Model>,deleteMany<Model>,upsertOne<Model> - Relations: Automatic 1-to-1, 1-to-many relation fields, plus relation count fields (e.g.,
user.posts,user.postsCount) - Paging & Sorting:
limit,offset,cursor,distinct, and multi-fieldorderBy(safely excluding list relations) - Filtering: Deep filtering powered by Prisma (
equals,contains,mode[Insensitive/Default],AND,OR,NOT,in,lt,lte, etc.) - Directives: Configure permissions, filters, defaults, field visibility (
readable), and mutability (writable) via schema comments (/// @pothos-generator ...) - Async Support: Asynchronous
authority,replace, and parameter callbacks supported out of the box - Built-in Scalars: Auto-registers
BigInt,DateTime,Json,Decimal, andBytesviagraphql-scalars
Installation
npm install pothos-prisma-generator
# or
pnpm add pothos-prisma-generator
# or
yarn add pothos-prisma-generatorPeer Dependencies
Ensure the following packages are installed in your project:
npm install @pothos/core @pothos/plugin-prisma @pothos/plugin-prisma-utils @prisma/client graphql(Optional: @pothos/plugin-scope-auth if using authScopes)
Setup
1. Configure prisma/schema.prisma
Add the pothosPrismaGenerator generator to generate the runtime DMMF:
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
generator pothos {
provider = "prisma-pothos-types"
generateDatamodel = true
}
generator pothosPrismaGenerator {
provider = "pothos-prisma-generator"
output = "./generated/prisma-dmmf.ts"
}Run prisma generate:
npx prisma generate2. Configure Pothos SchemaBuilder
Add PothosPrismaGeneratorPlugin to your SchemaBuilder:
import SchemaBuilder from "@pothos/core";
import PrismaPlugin from "@pothos/plugin-prisma";
import PrismaUtils from "@pothos/plugin-prisma-utils";
import ScopeAuthPlugin from "@pothos/plugin-scope-auth";
import PothosPrismaGeneratorPlugin from "pothos-prisma-generator";
import { PrismaClient } from "@prisma/client";
import { prismaDmmf } from "./generated/prisma-dmmf";
const prisma = new PrismaClient();
export interface Context {
user?: {
id: string;
roles: string[];
};
}
export const builder = new SchemaBuilder<{
Context: Context;
}>({
plugins: [
PrismaPlugin,
PrismaUtils,
ScopeAuthPlugin,
PothosPrismaGeneratorPlugin,
],
prisma: {
client: prisma,
dmmf: prismaDmmf,
},
pothosPrismaGenerator: {
// Dynamic replacement in directives (e.g. "%%USER%%" -> current user ID)
replace: {
"%%USER%%": ({ context }) => context.user?.id,
},
// User authority/roles function
authority: ({ context }) => context.user?.roles ?? [],
// Default includes
defaultIncludes: {
operations: true, // Default: true (all operations exposed unless excluded)
fields: true, // Default: true
},
},
});
export const schema = builder.toSchema();Directives (@pothos-generator)
You can control operation availability, permissions, default filters, and field accessibility directly inside schema.prisma using /// @pothos-generator documentation comments.
Directives follow the JSON5 format:
/// @pothos-generator <directiveName> <json5Params>Supported Operation Categories
query:findUnique,findFirst,findMany,countfind:findUnique,findFirst,findManycreate:createOne,createManyupdate:updateOne,updateManydelete:deleteOne,deleteManymutation: All create, update, delete operationsall: All queries and mutations
Directive Reference
1. operation - Filter exposed operations
Include or exclude specific GraphQL operations.
/// Include only createOne and updateOne
/// @pothos-generator operation {include:["createOne","updateOne"]}
/// Exclude deleteMany
/// @pothos-generator operation {exclude:["deleteMany"]}2. executable - Restrict execution permissions
Enforces permissions on operations. Raises an error if the user does not possess the required authority.
/// Mutations require USER role
/// @pothos-generator executable {include:["mutation"],authority:["USER"]}3. where - Enforce server-side filters
Automatically injects conditions into Prisma queries. If multiple directives match, the first matching directive is applied.
/// Admins can see all, standard users see only published records
/// @pothos-generator where {include:["query"],where:{},authority:["ADMIN"]}
/// @pothos-generator where {include:["query"],where:{published:true}}
/// Users can only update or delete their own records
/// @pothos-generator where {include:["update","delete"],where:{authorId:"%%USER%%"}}4. order - Default sort order
Specifies default sorting for queries.
/// @pothos-generator order {orderBy:{title:"asc"}}5. limit - Limit query result count
Caps the maximum number of items returned, preventing denial-of-service from unbounded queries.
/// Cap to 50 items maximum
/// @pothos-generator limit {limit:50}6. input-field - Control allowed input fields
Controls which fields can be specified in mutation input arguments.
/// Exclude internal fields from creation input
/// @pothos-generator input-field {fields:{exclude:["id","createdAt","updatedAt"]}}7. input-data - Auto-fill mutation data
Injects values into the data being saved. Values can use placeholders replaced by the replace builder option.
/// Automatically set authorId from logged-in user
/// @pothos-generator input-data {data:{authorId:"%%USER%%"}}8. option - Pass Pothos field options
Passes custom options directly to Pothos field definitions (e.g., ScopeAuth options).
/// @pothos-generator option {include:["mutation"],option:{authScopes:{authenticated:true}}}9. readable (Field directive) - Field visibility & access
Placed on individual model fields to restrict read access.
model User {
id String @id @default(uuid())
email String @unique
/// Only ADMIN can read roles
/// @pothos-generator readable ["ADMIN"]
roles String[]
/// Invisible in GraphQL schema (removed completely)
/// @pothos-generator readable []
secretToken String
}10. writable (Field directive) - Field mutation access
Placed on individual model fields to restrict or disable write access in mutations (createOne, createMany, updateOne, upsertOne).
- Setting
writable falsecompletely omits the field from all GraphQL input types. - Setting
writable ["ADMIN"](or{ authority: ["ADMIN"] }) validates user authority at mutation runtime and rejects unauthorized writes.
model User {
id String @id @default(uuid())
email String @unique
/// Never allow writing via mutations (excluded from input types)
/// @pothos-generator writable false
createdAt DateTime @default(now())
/// Only ADMIN can update or create with this field
/// @pothos-generator writable ["ADMIN"]
roles String[]
}Code API: Dynamic Model Extensions
You can also customize directives and add custom fields programmatically in TypeScript:
Adding Custom Fields to a Model
builder.addModelFields("User", {
fullName: (t) =>
t.string({
resolve: (parent) => `${parent.firstName} ${parent.lastName}`,
}),
});Adding Directives via Code
// Restrict operations
builder.addModelOperations("User", {
include: ["createOne", "updateOne", "findMany"],
});
// Add field directives
builder.addFieldDirectives("User", "roles", "readable", ["ADMIN"]);
// Add model options
builder.addModelOptions(
"User",
{ include: ["mutation"] },
{ authScopes: { ADMIN: true } }
);
// Parameter interceptor callback
builder.addModelParameterCallback((params, generatorParams) => {
if (generatorParams.modelName === "Post" && generatorParams.operationPrefix === "createOne") {
return {
...params,
input: {
...params.input,
authorId: generatorParams.params.ctx.user?.id,
},
};
}
return params;
});Sample Projects
- next-pothos (Next.js) - Deployed on Vercel
- nest-pothos (NestJS) - Deployed on Render
License
MIT
