Prisma Generator for Pothos Codegen.

Overview

Prisma Generator Pothos Codegen

This is a prisma generator that auto generate all input types for Crud Operations to Pothos. Use it as args for crud operations.

And generate all crud operations automatically. Optionally you can disable crud generation inside configs file. Just set: configs.crud.disabled to true

The roadmap:

  • Generator code for all input fields.
  • Generator for all Objects, Queries and Mutations. Something like prisma-tools do with Prisma and Nexus.

Getting Started

Install

yarn add prisma-generator-pothos-codegen or npm install prisma-generator-pothos-codegen

Usage

Add generator

generator client {
  provider = "prisma-client-js"
}

generator nexusPrisma {
   provider = "prisma-generator-pothos-codegen"
   generatorConfigPath = "../src/schema/configs.ts"
}

/// This is a user!
model User {
  /// This is an id!
  id  String  @id
}

Add scalar types to builder

import { Scalars } from 'prisma-generator-pothos-codegen'
import { Prisma } from '.prisma/client'

export const builder = new SchemaBuilder<{
  Scalars: Scalars<Prisma.Decimal, Prisma.InputJsonValue | null, Prisma.InputJsonValue>,
}>({
  ...
});

Import inputs from the generated file, and add as args.

import * as Inputs from './generated/inputs'

builder.queryFields((t) => ({
  findManyUser: t.field({
    type: [User],
    args: {
      where: t.arg({ type: Inputs.UserWhereInput }),
      orderBy: t.arg({ type: [Inputs.UserOrderByWithRelationInput] }),
      cursor: t.arg({ type: Inputs.UserWhereUniqueInput }),
      take: t.arg({ type: 'Int' }),
      skip: t.arg({ type: 'Int' }),
      distinct: t.arg({ type: [Inputs.UserScalarFieldEnum] }),
    },
    resolve: async (root, args) => {
      const user = await db.user.findMany({
        where: args.where || undefined,
        cursor: args.cursor || undefined,
        take: args.take || undefined,
        distinct: args.distinct || undefined,
        skip: args.skip || undefined,
        orderBy: args.orderBy || undefined,
      })

      return user
    }
  }),
}))

The generator currently supports a few options:

Key Default Value Description
generatorConfigPath ../src/schema/configs.ts Path to the configs file, from the schema path.
Click to see configs options
{
  inputs?: {
    prismaImporter?: string // default: import { Prisma } from ".prisma/client"
    builderImporter?: string // default: import { builder } from "./builder"
    excludeInputs?: string[] // default: undefined
    excludeScalars?: string[] // default: undefined
    outputFilePath?: string // path to generate file, from project root
    replacer?: (generated: string, position: ReplacerPosition) => string // a function to replace generated source
  },
  crud?: {
    disabled?: boolean // disable generaton of crud. default: false
    includeResolversExact?: string[] // generate only resolvers with name in the list. default: undefined. ie: ['createOneUser']
    includeResolversContain?: string[] // generate only resolvers with name included in the list. default: undefined. ie: ['User'].
    excludeResolversExact?: string[] // default: undefined. ie: ['createOneComment']
    excludeResolversContain?: string[] // default: undefined. ie: ['createOne']
    resolversImports?: string // default: what to import inside resolver
    dbCaller?: string // how to call prisma. default: context.db
    inputsImporter?: string // default: import * as Inputs from "@/generated/inputs";
    builderImporter?: string // default: import { builder } from "./builder"
    outputFolderPath?: string // path to generate files, from project root. default: ./generated
    replacer?: (generated: string, position: ReplacerPosition) => string // a function to replace generated source
  },
  global?: {
    replacer?: (generated: string, position: ReplacerPosition) => string // a function to replace generated source
  }
}

See example: click here


The tested environments:

Prisma Version Database State
3.12 - 4.00 Postgres - Sqlite

Example

Check for the example for a running sample image

Disclosures

Models with only relations

  • 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.

BigInt rename

  • As BigInt is reserved, we export Bigint for the BigInt scalar.

Publishing

  • Run npm run build
  • Run npm run pub
Comments
  • Exclude fields from input/object generation

    Exclude fields from input/object generation

    First of all, I love what you're doing here. I'd definitely see myself using this tool for a project I'm working on. To be able to use it, I would like to see a feature added to your tool. I'd be willing to submit a PR if you're tight on time, but I'd like to hear your thoughts first:

    I'd like to be able to hide certain fields at certain points in the graphql schema. Typegraphql-prisma provides this feature with an API I personally enjoy: https://prisma.typegraphql.com/docs/advanced/hiding-field

    model User {
      id        Int     @default(autoincrement()) @id
      email     String  @unique
      /// @TypeGraphQL.omit(input: true, output: true)
      password  String
    }
    

    Where the values for output may be true (to omit in all output cases) or ("create" | "update" | "where" | "orderBy")[]

    If I were to change anything about this api, it would be to:

    • have @Pothos.omit() be valid, meaning "hide this field everywhere"
    • don't have "create" | "update" | "where" | "orderBy" in quotes if possible (e.g. @Pothos.omit(input: [create, update]))
    • maybe ditch the object alltogether and use input and output as keys in an array of things you would want to omit (e.g. @Pothos.omit([create, update, output]), or @Pothos.omit([input]))

    Would love to hear your thoughts and if you would have time to implement this or a similar feature anytime soon!

    opened by saphewilliam 15
  • Example generates empty folders

    Example generates empty folders

    HI!, I was getting all empty folders on my project, so went to try the inputs-simple-sqlite example (deleting all the generated files) but got the same issue 🫤

    Repro: https://github.com/snake575/prisma-generator-pothos-example

    opened by snake575 5
  • Nexus-Prisma-like CRUD generation

    Nexus-Prisma-like CRUD generation

    This is the second of two Pull Requests (previous: #6) implementing the desired nexus-prisma-like feature set as discussed in #4

    This PR contains:

    • Updated CRUD generation to support adding to and modifying the generated code
    • Docs (README.md) update with example code.
    • Some minor code cleanup (made useTemplate type-safe, cleaned up filesystem code)

    This PR does not contain:

    • Updated tests
    • Updated logging
    • Updated examples
    opened by saphewilliam 3
  • Wrong enum list generation on graphql type

    Wrong enum list generation on graphql type

    Hi, this plugin is awesome and it helps me a lot. Thank you very much for that.

    I noticed a problem on the generation wich cause me to not be able to query the data after I created it.

    this is my prisma schema

    model TestCampaign {
      id   String @id @default(cuid())
      Unit Unit   @relation(fields: [unitId], references: [id])
    
      unitId       String
      ownerId      Int
      status       TestStatus @default(REQUESTED)
      test_request String
      type         TestType[]
      startedAt    DateTime?
      endedAt      DateTime?
    
      @@index([unitId])
    }
    
    enum TestStatus {
      REQUESTED
      IN_PROGRESS
      FINISHED
    }
    
    enum TestType {
      LOAD_OPTIMIZATION
      CONTROL
      PERFORMANCE
      MISC
    }
    

    the generation problem is on this line type TestType[] I can create the document because it expects an array. but I can't query it because it wants to give an enum key.

    in the object.base.ts, this is generated

    export const TestCampaignTypeFieldObject = defineFieldObject('TestCampaign', {
      type: Inputs.TestType,
      description: undefined,
      nullable: false,
      resolve: (parent) => parent.type,
    });
    

    there is a ts error on parent.type saying that TestType[] is cot compatible with "'MaybePromise<"LOAD_OPTIMIZATION" | "CONTROL" | "PERFORMANCE" | "MISC">'" Which is pretty logic because I asked for an array in my schema.

    When I query a TestCampaign, I have this error Enum "TestType" cannot represent value: ["CONTROL"] The weird thing is I can create it without a problem

    so I check on Apollo Studio and TestCampaign has this schema generated

    type TestCampaign {
      Unit: Unit!
      endedAt: DateTime
      id: ID!
      ownerId: Int!
      startedAt: DateTime
      status: TestStatus!
      test_request: String!
      type: TestType!     // this should be [TestType]!
      unitId: String!
    }
    

    and this is my pothos config

    // ./pothos.config.js
    /** @type {import('prisma-generator-pothos-codegen').Config} */
    module.exports = {
        inputs: {
            outputFilePath: './src/graphql/generated/inputs.ts',
        },
        crud: {
            outputDir: './src/graphql/generated/',
        },
        global: {
            builderImporter: `import { builder } from '../builder';`,
        },
    };
    

    Nothing fancy.

    so anyone has an idea whats missing ?

    Thanks guys

    opened by MeXaaR 2
  • Getting no output except empty folders and objects.d.ts

    Getting no output except empty folders and objects.d.ts

    Hi! Thanks for all your work!

    I'm having trouble getting this to work. Maybe I have the wrong idea about what it's supposed to do, but I though it would generate:

    • Basic types for use with Prisma with pothos extensions
    • A set of Input type
    • And a set of CRUD builder files.

    But I only get the first one. I tried both 0.1.0 and 0.2.2.

    This is my config:

    
    datasource db {
      provider = "sqlite"
      url      = env("DATABASE_URL")
    }
    
    generator client {
      provider      = "prisma-client-js"
      binaryTargets = ["native"]
    }
    
    generator pothos {
      provider     = "prisma-pothos-types"
      // Match client output location from above
      clientOutput = ".prisma/client"
      output       = "../node_modules/.prisma/client/objects.d.ts"
    }
    
    generator pathosCrud {
      provider            = "prisma-generator-pothos-codegen"
      generatorConfigPath = "../src/pothosCrud.js"
      output              = "./generated"
    }
    
    ....
    
    module.exports = {
      configs: {
        crud: {
          inputsImporter: 'import * as Inputs from "@/schema/inputs";',
          builderImporter: 'import { builder } from "@/schema/builder";',
          outputFolderPath: "./src/schema/",
          // replacer(generated, position) {
          //   return `// THIS CONTENT WAS INSERTED AT REPLACE. THE POSITION IS ${position}\n${generated}`
          // },
        },
        inputs: {
          prismaImporter: 'import { Prisma } from ".prisma/client";',
          outputFilePath: "./src/schema/inputs.ts",
        },
      },
    };
    

    The result is that I do get an objects.d.ts file and I get a set of folders in ./src/schema but I don't get an Inputs file, and I don't get anything in the folders. They are all empty.

    (Additionally, loading the config with es module support - import/export resulted in an error about the package not being a module.)

    If I'm doing something wrong, or my expectations are askew, please let me know! Thanks again for all you do.

    opened by CaptainN 2
  • Complicated schema leads to invalid inputs.ts

    Complicated schema leads to invalid inputs.ts

    For some reason, the schema below results in a generated inputs.ts file that does not type check. I tried to simplify it down to the smallest possible case, but there seems to be something about this schema in particular that causes it to fail. If I remove any part of it then it goes back to working correctly.

    model A {
      id String @id
      b  B[]
    }
    
    model B {
      id  String @id
      a   A      @relation(fields: [aId], references: [id])
      aId String
      int Int
      c   C[]
      d   D[]
      f   F[]
    }
    
    model C {
      id  String @id
      b   B      @relation(fields: [bId], references: [id])
      bId String
      int Int
      f   F[]
    }
    
    model D {
      id  String @id
      b   B      @relation(fields: [bId], references: [id])
      bId String
      f   F[]
    }
    
    model E {
      id String @id
      f  F[]
    }
    
    model F {
      id  String @id
      e   E      @relation(fields: [eId], references: [id])
      eId String
      b   B      @relation(fields: [bId], references: [id])
      bId String
      c   C[]
      d   D[]
    }
    
    opened by elektrica 2
  • Case issue when using snake case for model names

    Case issue when using snake case for model names

    First I want to say thank you for creating this. This is dope and very helpful!

    However I have noticed an issue with this plugin when using snake case names for models. I'm using this to build out an API for an existing database, and I have database with about 50 tables. All the names are snake case in the mysql database. So when generating the prisma schema, all the tables are snake case such as activity_feed. But when the generator runs, it's upper case in the inputs.ts file, but is lowercase in the generated files that point to it. So I immediately get errors because the variable is not matching.

    For example model activity_feed generates a variable in the inputs.ts file named Activity_feedScalarFieldEnum but then in the findMany.base.ts file, code is generated that looks like distinct: t.arg({ type: [Inputs.activity_feedScalarFieldEnum], required: false }), ... so the Inputs.activity_feedScalarFieldEnum does not match because the A is not a

    Can you please fix? Thank you!

    opened by chrisbull 1
  • Parse omit comments from prisma schema

    Parse omit comments from prisma schema

    This is the first of two Pull Requests implementing the desired nexus-prisma-like feature set proposed in #4

    This PR contains:

    • A text parser that parses @Pothos.omit() commands from the Prisma schema.
    • Rename configs to the more standardized config, and the exposed ConfigsOptions to Config
    • Separated Config (the user-defined config object) from ConfigInternal (the internally-used config object with default values inserted where the user has not specified a value) for better type-safety and DRY default values.
    • Renamed, reworked and removed various configuration options and made config a default export, so now it may be defined as such (inspired by Vite Docs):
    // config.js
    
    /** @type {import('prisma-generator-pothos-codegen').Config} */
    module.exports = {
      inputs: {
        outputFilePath: './src/graphql/__generated__/inputs.ts',
      },
      crud: { 
        outputDir: './src/graphql/__generated__/',
        inputsImporter: 'import * as Inputs from "@graphql/__generated__/inputs";',
      },
      global: {
        builderImporter: 'import { builder } from "@graphql/builder";',
      },
    };
    
    • Add linting and formatting to the repository
    • Restructure package.json dependencies such that they are installed correctly
    • Added MIT license field (because yarn was complaining, may be changed later)

    This PR does not do:

    • Updated docs on how @Pothos.omit() works
    • @Pothos.omit() testing
    • Any CRUD related stuff (that will be PR 2)
    opened by saphewilliam 1
  • Select queries & mutations to generate

    Select queries & mutations to generate

    Hi guys, maybe i didn't understand something in the doc but, it would be nice to be able to select queries & mutation to skip on the autogen

    like that for example

    /// @Pothos.omit(findMany, createMany, deleteMany)
    model User {
      id        String   @id @default(uuid())
      email     String
      password  String
    }
    

    is this already possible in a way I didn't get ?

    opened by MeXaaR 1
Releases(v0.4.0)
  • v0.4.0(Sep 7, 2022)

    Now, the generated code are base files for definition of objects, queries and mutations

    Optionally, these files can be "run" in bulk to generate the entire crud automatically.

    This changes everything, as now the generated code can be freely replaced, without affecting the customizations already made in the project and maintaining type safety.

    Thanks for @saphewilliam for the code that make this possible.

    Source code(tar.gz)
    Source code(zip)
  • v0.3.0(Aug 31, 2022)

    Inputs omit from Prisma Schema Comments

    Now its possible to omit fields from input generation, by adding comments inside Prisma Schema like:

    model User {
      ...
      /// @Pothos.omit()
      password  String
      ...
    }
    

    Details here: PR: https://github.com/Cauen/prisma-generator-pothos-codegen/pull/6 Issue: https://github.com/Cauen/prisma-generator-pothos-codegen/issues/4

    Thanks for @saphewilliam

    Source code(tar.gz)
    Source code(zip)
  • v0.2.3(Jul 29, 2022)

  • v0.2.0(Jul 13, 2022)

    Crud generator feature:

    Feature of generating crud with:

    • Objects
    • Queries
      • #{model}\queries\findUnique.ts
      • #{model}\queries\count.ts
      • #{model}\queries\findFirst.ts
      • #{model}\queries\findMany.ts
    • Mutations
      • #{model}\mutations\updateMany.ts
      • #{model}\mutations\updateOne.ts
      • #{model}\mutations\upsertOne.ts
      • #{model}\mutations\createMany.ts
      • #{model}\mutations\createOne.ts
      • #{model}\mutations\deleteMany.ts
      • #{model}\mutations\deleteOne.ts

    Now, configs is a file (set the path in generator):

    Click to see configs options
    {
      inputs?: {
        prismaImporter?: string // default: import { Prisma } from ".prisma/client"
        builderImporter?: string // default: import { builder } from "./builder"
        excludeInputs?: string[] // default: undefined
        excludeScalars?: string[] // default: undefined
        outputFilePath?: string // path to generate file, from project root
        replacer?: (generated: string, position: ReplacerPosition) => string // a function to replace generated source
      },
      crud?: {
        disabled?: boolean // disable generaton of crud. default: false
        includeResolversExact?: string[] // generate only resolvers with name in the list. default: undefined. ie: ['createOneUser']
        includeResolversContain?: string[] // generate only resolvers with name included in the list. default: undefined. ie: ['User'].
        excludeResolversExact?: string[] // default: undefined. ie: ['createOneComment']
        excludeResolversContain?: string[] // default: undefined. ie: ['createOne']
        resolversImports?: string // default: what to import inside resolver
        dbCaller?: string // how to call prisma. default: context.db
        inputsImporter?: string // default: import * as Inputs from "@/generated/inputs";
        builderImporter?: string // default: import { builder } from "./builder"
        outputFolderPath?: string // path to generate files, from project root. default: ./generated
        replacer?: (generated: string, position: ReplacerPosition) => string // a function to replace generated source
      },
      global?: {
        replacer?: (generated: string, position: ReplacerPosition) => string // a function to replace generated source
      }
    }
    

    See example: click here

    Source code(tar.gz)
    Source code(zip)
  • v0.1.0(Jul 9, 2022)

    Features:

    • Generate all Input Types (in a custom path)
    • Generate NEVER type, if empty fields.
    • Ignore types
    • Ignore scalars
    • Examples (postgres + sqlite)

    Tested with Sqlite and Postgres Tested with Prisma 3.12 -> 4.0.0

    Source code(tar.gz)
    Source code(zip)
Owner
Emanuel
Using technology to bring projects to life. Full Stack Developer currently engaged in Reactjs, Nodejs, Typescript and Graphql
Emanuel
Prisma +2 generator to emit Yup schemas from your Prisma schema

Prisma Yup Generator Automatically generate Yup schemas from your Prisma Schema, and use them to validate your API endpoints or any other use you have

Omar Dulaimi 31 Dec 24, 2022
Prisma 2+ generator to emit Joi schemas from your Prisma schema

Prisma Joi Generator Automatically generate Joi schemas from your Prisma Schema, and use them to validate your API endpoints or any other use you have

Omar Dulaimi 26 Dec 24, 2022
Prisma +2 generator to emit a tRPC shield from your Prisma schema

Prisma tRPC Shield Generator Automatically generate a tRPC Shield from your Prisma Schema. Updates every time npx prisma generate runs. Table of Conte

Omar Dulaimi 27 Dec 24, 2022
Prisma 2+ generator to emit Zod schemas from your Prisma schema

Prisma Zod Generator Automatically generate Zod schemas from your Prisma Schema, and use them to validate your API endpoints or any other use you have

Omar Dulaimi 212 Dec 27, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
NextJS with GraphQL using type-graphl and graphql-codegen adoptable dogs example code

This is a Next.js project bootstrapped with create-next-app. Getting Started First, run the development server: npm run dev # or yarn dev Open http://

Jack Herrington 2 Mar 31, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
This is a library to alternate and self-host the Prisma Data Proxy (cloud.prisma.io)

Alternative Prisma Data Proxy This is a library to alternate and self-host the Prisma Data Proxy (cloud.prisma.io). In order to deploy your project to

AijiUejima 60 Dec 28, 2022
Prisma 2+ generator to emit fully implemented tRPC routers

Prisma tRPC Generator Automatically generate fully implemented tRPC routers from your Prisma Schema. This includes routers, app router and of course a

Omar Dulaimi 370 Jan 3, 2023
Prisma 2+ generator to emit a JSON file that can be run with json-server

Prisma JSON Server Generator A Prisma generator that automates creating a JSON file that can be run as a server from your Prisma schema. Explore the o

Omar Dulaimi 14 Jan 7, 2023
Obsidian text generator Plugin Text generator using GPT-3 (OpenAI)

is a handy plugin for Obsidian that helps you generate text content using the powerful language model GP

null 356 Dec 29, 2022
Types generator will help user to create TS types from JSON. Just paste your single object JSON the Types generator will auto-generate the interfaces for you. You can give a name for the root object

Types generator Types generator is a utility tool that will help User to create TS Interfaces from JSON. All you have to do is paste your single objec

Vineeth.TR 16 Dec 6, 2022
My-portfolio - Built with Namecheap, Digital Ocean, Nginx, PM2, SSL, NextJs, Tailwind 3, Graphql, NexusJS, Prisma, Postgres, Passion and Love

Current Implementation technologies Nextjs with Typescript. Static pages/ Server side rendering. Easy peasy state management (Might not need it with i

Samrood Ali 1 Jan 10, 2022
A Feathers service adapter for Prisma ORM.

feathers-prisma A Feathers service adapter for Prisma ORM. Installation npm install feathers-prisma --save Documentation This adapter supports all me

Phil 27 Dec 9, 2022
Create a C# .NET core EntityFramework ORM from your schema.prisma file

A note of forewarning to the would-be user... This was a failure. I'm making a note here: huge regret. It's hard to overstate my dissatisfaction. ?? S

Ian Ray 9 Dec 24, 2022
This repository aims to create a POC about authentication and authorization using NestJS, Prisma and JWT.

A progressive Node.js framework for building efficient and scalable server-side applications. Description Nest framework TypeScript starter repository

Vinícius Fraga Modesto 2 Nov 2, 2022
Talk about Azure SQL + Prisma

Talk - Power Up Your BackEnd Applications with Serverless Architecture & Azure SQL A demo related with the talk Power Up Your BackEnd Applications wit

Glaucia Lemos 10 Sep 13, 2022
Express.js framework boilerplate with TypeScript, Prisma, ESLint, Husky and Jest

Setup a Node.js project with Typescript, Prisma ESLint, Prettier, Husky Node.js boilerplate with Express.js, TypeScript, Prisma, ESLint, Prettier, Hus

Smart Geek 6 Dec 12, 2022