{"id":14974120,"url":"https://github.com/cauen/prisma-generator-pothos-codegen","last_synced_at":"2025-07-28T14:39:06.407Z","repository":{"id":43879779,"uuid":"511679246","full_name":"Cauen/prisma-generator-pothos-codegen","owner":"Cauen","description":"The fastest way to create a fully customizable CRUD Graphql API from Prisma Schema.","archived":false,"fork":false,"pushed_at":"2024-10-08T12:25:39.000Z","size":1121,"stargazers_count":104,"open_issues_count":13,"forks_count":20,"subscribers_count":6,"default_branch":"master","last_synced_at":"2025-04-04T00:11:27.655Z","etag":null,"topics":["api","codegen","crud","crud-api","crud-api-node","generator","graphql","pothos","prisma","typescript"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/prisma-generator-pothos-codegen","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Cauen.png","metadata":{"files":{"readme":"README.md","changelog":"changelog.md","contributing":"CONTRIBUTING.md","funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-07-07T21:28:52.000Z","updated_at":"2025-03-24T10:00:41.000Z","dependencies_parsed_at":"2024-06-19T05:27:54.914Z","dependency_job_id":"7da08603-cb28-4056-86a6-4f6bdfc125db","html_url":"https://github.com/Cauen/prisma-generator-pothos-codegen","commit_stats":{"total_commits":201,"total_committers":11,"mean_commits":"18.272727272727273","dds":"0.24378109452736318","last_synced_commit":"5bd10aacf287039a447a01eda12f39b2fb7c8be7"},"previous_names":[],"tags_count":16,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Cauen%2Fprisma-generator-pothos-codegen","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Cauen%2Fprisma-generator-pothos-codegen/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Cauen%2Fprisma-generator-pothos-codegen/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Cauen%2Fprisma-generator-pothos-codegen/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Cauen","download_url":"https://codeload.github.com/Cauen/prisma-generator-pothos-codegen/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248631687,"owners_count":21136556,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","codegen","crud","crud-api","crud-api-node","generator","graphql","pothos","prisma","typescript"],"created_at":"2024-09-24T13:49:59.266Z","updated_at":"2025-04-12T20:44:07.557Z","avatar_url":"https://github.com/Cauen.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Prisma Generator Pothos Codegen\n\n![Group 1](https://github.com/Cauen/prisma-generator-pothos-codegen/assets/8796757/19f6cdbe-44f5-40ac-8b9b-326c49c1c281)\n\nA [prisma](https://www.prisma.io/) [generator](https://www.prisma.io/docs/concepts/components/prisma-schema/generators) plugin that auto-generates [Pothos](https://pothos-graphql.dev/) GraphQL input types and crud operations (all queries and mutations).\n\nEasily convert a prisma schema into a full graphql CRUD API.\n\nOn `prisma generate` we create:\n\n- All [input types](https://pothos-graphql.dev/docs/guide/inputs) for `Create`, `Find`, `Update`, `Sort` and `Delete` operations (to be used as args in [fields](https://pothos-graphql.dev/docs/guide/fields#arguments)).\n- (Optional): Create all `Objects`, `Queries` and `Mutations` base files (to create customizable resolvers).\n- (Optional): Execute all these base files without customization to create a default CRUD.\n\n## Table of Contents\n\n\u003c!-- toc --\u003e\n\n- [Getting Started](#getting-started)\n  * [Install](#install)\n  * [Peer dependencies](#peer-dependencies)\n  * [Set Up](#set-up)\n    + [Add the generator to your schema.prisma](#add-the-generator-to-your-schemaprisma)\n    + [Add scalar types to the builder](#add-scalar-types-to-the-builder)\n    + [Create a configuration file (optional)](#create-a-configuration-file--optional-)\n    + [Run the generator](#run-the-generator)\n- [Usage](#usage)\n  * [Inputs](#inputs)\n  * [Objects](#objects)\n  * [Queries and Mutations](#queries-and-mutations)\n  * [Auto define all `objects`, `queries` and `mutations` (crud operations)](#auto-define-all--objects----queries--and--mutations---crud-operations-)\n  * [Examples](#examples)\n- [Disclosures](#disclosures)\n  * [Models with only relations](#models-with-only-relations)\n  * [BigInt rename](#bigint-rename)\n\n\u003c!-- tocstop --\u003e\n\n## Getting Started\n\n### Install\n\nUsing yarn\n\n```sh\nyarn add -D prisma-generator-pothos-codegen\n```\n\nor using npm\n\n```sh\nnpm install --save-dev prisma-generator-pothos-codegen\n```\n\n### Peer dependencies\n\nThe package has been developed and tested up to the following peer dependencies (see updated [example](/examples/inputs-simple-sqlite)):\n\n\u003c!-- TODO Maybe we could have some sort of automated pipeline that tests different versions of these peer deps? --\u003e\n\n```\n\"@pothos/core\": \"^4.0.2\",\n\"@pothos/plugin-prisma\": \"^4.0.3\"\",\n\"@prisma/client\": \"^5.15.1\",\n\"prisma\": \"^5.15.1\",\n```\n\nUsing higher versions may break something. In these cases, please open a new issue.\n\n### Set Up\n\n#### Add the generator to your schema.prisma\n\n```prisma\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n\ngenerator pothos {\n  provider = \"prisma-pothos-types\"\n}\n\ngenerator pothosCrud {\n  provider = \"prisma-generator-pothos-codegen\"\n  generatorConfigPath = \"./pothos.config.js\"\n  // You may also set the `generatorConfigPath` via the `POTHOS_CRUD_CONFIG_PATH` environment variable.\n  // The environment variable will override the path hardcoded here.\n}\n\n/// This is a user!\nmodel User {\n  /// This is an id!\n  id  String  @id\n}\n```\n\n#### Add scalar types to the builder\n\n```ts\nimport { Scalars } from 'prisma-generator-pothos-codegen';\nimport { Prisma } from '.prisma/client';\n\nexport const builder = new SchemaBuilder\u003c{\n  // ... Context, plugins? ...\n  PrismaTypes: PrismaTypes; // required for @pothos/plugin-prisma integration (which is required)\n  Scalars: Scalars\u003cPrisma.Decimal, Prisma.InputJsonValue | null, Prisma.InputJsonValue\u003e; // required to define correct types for created scalars.\n}\u003e({\n  // Other builder config\n});\n```\n\n#### Create a configuration file (optional)\n\n```js\n// ./pothos.config.js\n\n/** @type {import('prisma-generator-pothos-codegen').Config} */\nmodule.exports = {\n  inputs: {\n    outputFilePath: './src/graphql/__generated__/inputs.ts',\n  },\n  crud: {\n    outputDir: './src/graphql/__generated__/',\n    inputsImporter: `import * as Inputs from '@graphql/__generated__/inputs';`,\n    resolverImports: `import prisma from '@lib/prisma';`,\n    prismaCaller: 'prisma',\n  },\n  global: {\n  },\n};\n```\n\n\u003cdetails\u003e\n  \u003csummary\u003eClick to see all configuration options\u003c/summary\u003e\n\n  ```ts\n  {\n    /** Input type generation config */\n    inputs?: {\n      /** Create simpler inputs for easier customization and ~65% less generated code. Default: `false` */\n      simple?: boolean;\n      /** How to import the Prisma namespace. Default: `\"import { Prisma } from '.prisma/client';\"` */\n      prismaImporter?: string;\n      /** Path to generate the inputs file to from project root. Default: `'./generated/inputs.ts'` */\n      outputFilePath?: string;\n      /** List of excluded scalars from generated output */\n      excludeScalars?: string[];\n      /** A function to replace generated source. Combined with global replacer config */\n      replacer?: Replacer\u003c'inputs'\u003e;\n      /** Map all Prisma fields with \"@id\" attribute to Graphql \"ID\" Scalar.\n       *\n       * ATTENTION: Mapping non String requires a conversion inside resolver, once GraphQl ID Input are coerced to String by definition. Default: false */\n      mapIdFieldsToGraphqlId?: false | 'WhereUniqueInputs';\n    };\n    /** CRUD generation config */\n    crud?: {\n      /** Disable generaton of crud. Default: `false` */\n      disabled?: boolean;\n      /** How to import the inputs. Default `\"import * as Inputs from '../inputs';\"` */\n      inputsImporter?: string;\n      /** How to import the Prisma namespace at the objects.ts file. Default `\"import { Prisma } from '.prisma/client';\"`. Please use \"resolverImports\" to import prismaClient at resolvers. */\n      prismaImporter?: string;\n      /** How to call the prisma client. Default `'_context.prisma'` */\n      prismaCaller?: string;\n      /** Any additional imports you might want to add to the resolvers (e.g. your prisma client). Default: `''` */\n      resolverImports?: string;\n      /** Directory to generate crud code into from project root. Default: `'./generated'` */\n      outputDir?: string;\n      /** A function to replace generated source. Combined with global replacer config */\n      replacer?: Replacer\u003c'crud'\u003e;\n      /** A boolean to enable/disable generation of `autocrud.ts` which can be imported in schema root to auto generate all crud objects, queries and mutations. Default: `true` */\n      generateAutocrud?: boolean;\n      /** An array of parts of resolver names to be excluded from generation. Ie: [\"User\"] Default: [] */\n      excludeResolversContain?: string[];\n      /** An array of resolver names to be excluded from generation. Ie: [\"upsertOneComment\"] Default: [] */\n      excludeResolversExact?: string[];\n      /** An array of parts of resolver names to be included from generation (to bypass exclude contain). Ie: if exclude [\"User\"], include [\"UserReputation\"] Default: [] */\n      includeResolversContain?: string[];\n      /** An array of resolver names to be included from generation (to bypass exclude contain). Ie: if exclude [\"User\"], include [\"UserReputation\"] Default: [] */\n      includeResolversExact?: string[];\n      /** Caution: This delete the whole folder (Only use if the folder only has auto generated contents). A boolean to delete output dir before generate. Default: False */\n      deleteOutputDirBeforeGenerate?: boolean;\n      /** Export all crud queries/mutations/objects in objects.ts at root dir. Default: true */\n      exportEverythingInObjectsDotTs?: boolean;\n      /** Map all Prisma fields with \"@id\" attribute to Graphql \"ID\" Scalar. Default: 'Objects' */\n      mapIdFieldsToGraphqlId?: false | 'Objects';\n      /** Change the generated variables from object.base.ts from something like `UserName` to `User_Name`. This avoids generated duplicated names in some cases. See [issue #58](https://github.com/Cauen/prisma-generator-pothos-codegen/issues/58). Default: false */\n      underscoreBetweenObjectVariableNames?: false | 'Objects';\n    };\n    /** Global config */\n    global?: {\n      /** A function to replace generated source */\n      replacer?: Replacer;\n      /** Location of builder to replace in all files. Relative to package root. ie: './src/schema/builder'. Default: './builder' */\n      builderLocation?: string;\n      /** Run function before generate */\n      beforeGenerate?: (dmmf: DMMF.Document) =\u003e void;\n      /** Run function after generate */\n      afterGenerate?: (dmmf: DMMF.Document) =\u003e void;\n    };\n  }\n  ```\n\u003c/details\u003e\n\u003cbr/\u003e\n\n#### Run the generator\n\n```sh\nyarn prisma generate\n```\n\nor\n\n```sh\nnpx prisma generate\n```\n\n## Usage\n\n###  Inputs\n\nYou can use `@Pothos.omit()` function calls in your prisma schema field descriptions to control which fields are used in the generated input types.\n\n- `@Pothos.omit()` Omits the field from all inputs\n- `@Pothos.omit(create)` Omits field from the create input\n- `@Pothos.omit(orderBy, where, update)` Omits field from the orderBy, where, and update inputs, but not the create input\n\nThe available options are `create`, `update`, `where`, and `orderBy`.\n\n```prisma\nmodel User {\n  /// @Pothos.omit(create, update)\n  id        String   @id @default(uuid())\n  email     String\n  /// @Pothos.omit()\n  password  String\n}\n```\n\nYou can also augment/derive new inputs from the generated `inputs.ts` file.\n\n```ts\n// ./src/graphql/User/inputs.ts\n\nimport { Prisma } from '@prisma/client';\n// Import generated input fields definition\nimport { UserUpdateInputFields } from '@/graphql/__generated__/inputs';\n\n// Note: you can't use `builder.inputType` to generate this new input\nexport const UserUpdateInputCustom = builder\n  .inputRef\u003cPrisma.UserUpdateInput \u0026 { customArg: string }\u003e('UserUpdateInputCustom')\n  .implement({\n    fields: (t) =\u003e ({\n      ...UserUpdateInputFields(t),\n      customArg: t.field({ required: true, type: 'String' }),\n    }),\n  });\n```\n\n### Objects\n\n```ts\n// ./src/graphql/User/object.ts\n\nimport { UserObject } from '@/graphql/__generated__/User';\nimport { builder } from '@/graphql/builder'; // Pothos schema builder\n\n// Use the Object export to accept all default generated query code\nbuilder.prismaObject('User', UserObject);\n\n// Or modify it as you wish\nbuilder.prismaObject('User', {\n  ...UserObject,\n  fields: (t) =\u003e {\n    // Type-safely omit and rename fields\n    const { password: _password, email: emailAddress, ...fields } = UserObject.fields(t);\n    const sessionsField = UserSessionsFieldObject(t);\n\n    return {\n      ...fields,\n      // Renamed field\n      emailAddress,\n      // Edit and extend field\n      sessions: t.relation('sessions', {\n        ...sessionsField,\n        args: { ...sessionsField.args, customArg: t.arg({ type: 'String', required: false }) },\n        authScopes: { admin: true },\n      }),\n      // Add custom fields\n      customField: t.field({ type: 'String', resolve: () =\u003e 'Hello world!' }),\n    };\n  },\n});\n```\n\n### Queries and Mutations\n\n```ts\n// ./src/graphql/User/query.ts\n\nimport { findManyUserQuery, findManyUserQueryObject } from '@/graphql/__generated__/User';\nimport { builder } from '@/graphql/builder'; // Pothos schema builder\n\n// Use the Query exports to accept all default generated query code\nbuilder.queryFields(findManyUserQuery);\n\n// Use the QueryObject exports to override or add to the generated code\nbuilder.queryFields((t) =\u003e {\n  const field = findManyUserQueryObject(t);\n  return {\n    findManyUser: t.prismaField({\n      // Inherit all the generated properties\n      ...field,\n\n      // Modify the args and use custom arg in a custom resolver\n      args: { ...field.args, customArg: t.arg({ type: 'String', required: false }) },\n      resolve: async (query, root, args, context, info) =\u003e {\n        const { customArg } = args;\n        console.log(customArg);\n        return field.resolve(query, root, args, context, info);\n      },\n\n      // Add an custom extension\n      authScopes: { admin: true },\n    }),\n  };\n});\n```\n\n### Auto define all `objects`, `queries` and `mutations` (crud operations)\n\nFirst, make sure that `options.crud.generateAutocrud` isn't set to `false`\n\n```ts\n// ./src/schema/index.ts (import autocrud.ts)\nimport {\n  generateAllCrud,\n  generateAllObjects,\n  generateAllQueries,\n  generateAllMutations\n} from '@/graphql/__generated__/autocrud.ts',\nimport { builder } from '@/graphql/builder'; // Pothos schema builder\n\n// (option 1) generate all objects, queries and mutations\ngenerateAllCrud()\n\n// (option 2) or create them separately\ngenerateAllObjects()\ngenerateAllQueries()\ngenerateAllMutations()\n\n// (option 3) or limit crud generation\ngenerateAllObjects({ include: [\"User\", \"Profile\", 'Comment'] })\ngenerateAllQueries({ exclude: [\"Comment\"] })\ngenerateAllMutations({ exclude: [\"User\"] })\n\n// Defining schema roots\nbuilder.queryType({});\nbuilder.mutationType({});\n\nexport const schema = builder.toSchema({});\n```\n\nGenerated queries:\n\n- count\n- findFirst\n- findMany\n- findUnique\n\nGenerated mutations:\n\n- createMany\n- createOne\n- deleteMany\n- deleteOne\n- updateMany\n- updateOne\n- upsertOne\n\n### Examples\n\nCheck for the [example](/examples/inputs-simple-sqlite) for a running sample\n\n![image](https://user-images.githubusercontent.com/8796757/222917186-9a88f5e9-27c6-44b5-8653-fa9efb0aa255.png)\n\n## Disclosures\n\n### Models with only relations\n\n- We create a custom scalar `NEVER` that avoids this error: `Input Object type FollowUpdateManyMutationInput must define one or more fields.` from Graphql. if you have models that are relations-only. Like N-N fields without `no relation fields` or id-only models, we set field `_` of some operations to this scalar. If you fill this fake property, the operation will result in a error.\n\n### BigInt rename\n\n- As `BigInt` is reserved, we export `Bigint` for the BigInt scalar.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcauen%2Fprisma-generator-pothos-codegen","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcauen%2Fprisma-generator-pothos-codegen","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcauen%2Fprisma-generator-pothos-codegen/lists"}