Prisma 2+ generator to emit fully implemented tRPC routers

Overview

Prisma tRPC Generator

npm version npm HitCount npm

Automatically generate fully implemented tRPC routers from your Prisma Schema. This includes routers, app router and of course all input schemas using zod. Updates every time npx prisma generate runs.

Table of Contents

Installation

Using npm:

 npm install prisma-trpc-generator

Using yarn:

 yarn add prisma-trpc-generator

Usage

1- Star this repo 😉

2- Add the generator to your Prisma schema

generator trpc {
  provider = "prisma-trpc-generator"
}

3- Running npx prisma generate for the following schema.prisma

model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
  posts Post[]
}

model Post {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  title     String
  content   String?
  published Boolean  @default(false)
  viewCount Int      @default(0)
  author    User?    @relation(fields: [authorId], references: [id])
  authorId  Int?
}

will generate

tRPC Routers

4- Don't forget to supply your createContext function inside ./routers/helpers/createRouter.ts. You should check the official tRPC docs for reference.

Additional Options

Option  Description Type  Default
output Output directory for the generated routers and zod schemas string ./generated

Use additional options in the schema.prisma

generator trpc {
  provider   = "prisma-trpc-generator"
  output     = "./trpc"
}
Comments
  • Thoughts on protecting some methods behind authentication and permissions

    Thoughts on protecting some methods behind authentication and permissions

    Problem

    Currently, this generator can't be used whenever there needs to be permission per procedure. For example, only some users are supposed to have access to a procedure. Or a procedure requires the user to contain a specific scope in their JWT.

    Suggested solution

    Add a way to pass information into the generator (maybe directives in the Prisma file?)

    Alternatives

    Manually write all tRPC procedures by hand.

    enhancement 
    opened by TheBestMoshe 12
  • Invalid types for the

    Invalid types for the "groupBy" function

    Bug description

    There is an invalid type error in the case of the groupBy function for all the generated routers. I am building a Next.js app (with Typescript) and it fails during the build process with the following error:

    /prisma/generated/routers/Account.router.ts:91:63
    Type error: Argument of type '{ where?: AccountWhereInput | undefined; orderBy?: AccountOrderByWithAggregationInput | AccountOrderByWithAggregationInput[] | undefined; take?: number | undefined; skip?: number | undefined; having?: AccountScalarWhereWithAggregatesInput | undefined; by: ("id" | ... 10 more ... | "session_state")[]; }' is not assignable to parameter of type '{ where?: AccountWhereInput | undefined; orderBy?: AccountOrderByWithAggregationInput | AccountOrderByWithAggregationInput[] | undefined; take?: number | undefined; skip?: number | undefined; having?: AccountScalarWhereWithAggregatesInput | undefined; by: ("id" | ... 10 more ... | "session_state")[]; } & { ...; }'.
      Type '{ where?: AccountWhereInput | undefined; orderBy?: AccountOrderByWithAggregationInput | AccountOrderByWithAggregationInput[] | undefined; take?: number | undefined; skip?: number | undefined; having?: AccountScalarWhereWithAggregatesInput | undefined; by: ("id" | ... 10 more ... | "session_state")[]; }' is not assignable to type '{ orderBy: Enumerable<AccountOrderByWithAggregationInput> | undefined; }'.
        Property 'orderBy' is optional in type '{ where?: AccountWhereInput | undefined; orderBy?: AccountOrderByWithAggregationInput | AccountOrderByWithAggregationInput[] | undefined; take?: number | undefined; skip?: number | undefined; having?: AccountScalarWhereWithAggregatesInput | undefined; by: ("id" | ... 10 more ... | "session_state")[]; }' but required in type '{ orderBy: Enumerable<AccountOrderByWithAggregationInput> | undefined; }'.
    
      89 |     input: AccountGroupBySchema,
      90 |     async resolve({ ctx, input }) {
    > 91 |       const groupByAccount = await ctx.prisma.account.groupBy(input);
         |                                                               ^
      92 |       return groupByAccount;
      93 |     },
      94 |   })
    

    How to reproduce

    1. Create a Next.js project with a T3-stack
    2. Install prisma-trpc-generator package
    3. Try to build the app

    Expected behavior

    The routers should have the correct types for the groupBy functions, resulting in the app being successfully built.

    Prisma information

    generator client {
      provider = "prisma-client-js"
    }
    
    generator trpc {
      provider       = "prisma-trpc-generator"
      withMiddleware = false
      withShield     = false
      contextPath    = "../../../../src/context"
    }
    
    datasource db {
      provider = "sqlite"
      // NOTE: When using postgresql, mysql or sqlserver, uncomment the @db.Text annotations in model Account below
      // Further reading:
      // https://next-auth.js.org/adapters/prisma#create-the-prisma-schema
      // https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#string
      url      = env("DATABASE_URL")
    }
    
    model Example {
      id        String   @id @default(cuid())
      createdAt DateTime @default(now())
      updatedAt DateTime @updatedAt
    }
    
    // Necessary for Next auth
    model Account {
      id                String  @id @default(cuid())
      userId            String
      type              String
      provider          String
      providerAccountId String
      refresh_token     String? // @db.Text
      access_token      String? // @db.Text
      expires_at        Int?
      token_type        String?
      scope             String?
      id_token          String? // @db.Text
      session_state     String?
      user              User    @relation(fields: [userId], references: [id], onDelete: Cascade)
    
      @@unique([provider, providerAccountId])
    }
    
    model Session {
      id           String   @id @default(cuid())
      sessionToken String   @unique
      userId       String
      expires      DateTime
      user         User     @relation(fields: [userId], references: [id], onDelete: Cascade)
    }
    
    model User {
      id            String    @id @default(cuid())
      name          String?
      email         String?   @unique
      emailVerified DateTime?
      image         String?
      accounts      Account[]
      sessions      Session[]
    }
    
    model VerificationToken {
      identifier String
      token      String   @unique
      expires    DateTime
    
      @@unique([identifier, token])
    }
    

    Environment & setup

    • OS: Mac OS
    • Database: SQLite
    • Node.js version: 18.12.1

    Prisma Version

    Environment variables loaded from .env
    prisma                  : 4.6.1
    @prisma/client          : 4.6.1
    Current platform        : darwin-arm64
    Query Engine (Node-API) : libquery-engine 694eea289a8462c80264df36757e4fdc129b1b32 (at node_modules/@prisma/engines/libquery_engine-darwin-arm64.dylib.node)
    Migration Engine        : migration-engine-cli 694eea289a8462c80264df36757e4fdc129b1b32 (at node_modules/@prisma/engines/migration-engine-darwin-arm64)
    Introspection Engine    : introspection-core 694eea289a8462c80264df36757e4fdc129b1b32 (at node_modules/@prisma/engines/introspection-engine-darwin-arm64)
    Format Binary           : prisma-fmt 694eea289a8462c80264df36757e4fdc129b1b32 (at node_modules/@prisma/engines/prisma-fmt-darwin-arm64)
    Format Wasm             : @prisma/prisma-fmt-wasm 4.6.1-3.694eea289a8462c80264df36757e4fdc129b1b32
    Default Engines Hash    : 694eea289a8462c80264df36757e4fdc129b1b32
    Studio                  : 0.476.0
    
    bug 
    opened by qmo-harpuneetghuman 5
  • Support Include and Select

    Support Include and Select

    Discussed in https://github.com/omar-dulaimi/prisma-trpc-generator/discussions/11

    This requires work to be done here in this library and also in Prisma Zod Generator.

    enhancement help wanted 
    opened by omar-dulaimi 5
  • Ability to not generate certain routers

    Ability to not generate certain routers

    Problem

    Some of the models created in Prisma schema are not meant to be touched by the frontend at all. As an example, VerificationToken from the NextAuth is not something I want to be able to interact with from the client-side - I want to leave it to NextAuth to deal with it.

    Suggested solution

    It would be great to be able to disable the generation of a router for the Prisma model by using a simple comment, something like following:

    // @trpc-ignore
    model VerificationToken {
      ...
    }
    

    I understand that it's not as straightforward as just ignoring the model, since other models might reference the ignored one. In this case, the other model's router should also not include the ignored model, so the property that references it should be removed.

    Alternatives

    If this feature already exists, would be nice to have it documented in README

    enhancement 
    opened by bring-shrubbery 4
  • Missing Aggregate field in schema.

    Missing Aggregate field in schema.

    Discussed in https://github.com/omar-dulaimi/prisma-trpc-generator/discussions/23

    Originally posted by Revitate August 6, 2022 From prisma document (https://www.prisma.io/docs/reference/api-reference/prisma-client-reference#aggregate) and generated schema image I think it has missing field _count, _avg, _sum, _min and _max in InputSchema. Can you help me?

    bug 
    opened by omar-dulaimi 4
  • Generator doesn't generate schema from column type decimal

    Generator doesn't generate schema from column type decimal

    Bug description

    Prisma trpc generator doesn't generate some column type from schema.

    How to reproduce

    Expected behavior

    Need to support column type same as prisma

    Prisma information

    generator client {
      provider               = "prisma-client-js"
      output                 = "./client"
      customPrismaImportPath = "../client"
    }
    
    generator trpc {
      provider       = "prisma-trpc-generator"
      withMiddleware = false
      withShield     = false
      contextPath    = "../../../../src/context"
      output         = "./trpc"
    }
    
    datasource db {
      provider = "mysql"
      url      = env("DATABASE_URL")
    }
    
    generator zod {
      provider = "zod-prisma"
      output   = "./zod" // (default) the directory where generated zod schemas will be saved
    
      relationModel = true // (default) Create and export both plain and related models.
      // relationModel         = "default" // Do not export model without relations.
      // relationModel         = false // Do not generate related model
    
      // modelCase                = "PascalCase" // (default) Output models using pascal case (ex. UserModel, PostModel)
      modelCase = "camelCase" // Output models using camel case (ex. userModel, postModel)
    
      modelSuffix = "Model" // (default) Suffix to apply to your prisma models when naming Zod schemas
    
      // useDecimalJs          = false // (default) represent the prisma Decimal type using as a JS number
      useDecimalJs = true // represent the prisma Decimal type using Decimal.js (as Prisma does)
    
      // https://www.prisma.io/docs/concepts/components/prisma-client/working-with-fields/working-with-json-fields#filtering-by-null-values
      prismaJsonNullability = true // (default) uses prisma's scheme for JSON field nullability
      // prismaJsonNullability = false // allows null assignment to optional JSON fields
    }
    
    model Test {
        amount      Decimal?     @db.Decimal(9, 2)
    }
    

    Environment & setup

    • OS: Mac OS
    • Database: MySQL
    • Node.js version: 14.7.3

    Prisma Version

    prisma                  : 4.1.1
    @prisma/client          : 4.1.1
    Current platform        : darwin-arm64
    Query Engine (Node-API) : libquery-engine 8d8414deb360336e4698a65aa45a1fbaf1ce13d8 (at ../../node_modules/prisma/node_modules/@prisma/engines/libquery_engine-darwin-arm64.dylib.node)
    Migration Engine        : migration-engine-cli 8d8414deb360336e4698a65aa45a1fbaf1ce13d8 (at ../../node_modules/prisma/node_modules/@prisma/engines/migration-engine-darwin-arm64)
    Introspection Engine    : introspection-core 8d8414deb360336e4698a65aa45a1fbaf1ce13d8 (at ../../node_modules/prisma/node_modules/@prisma/engines/introspection-engine-darwin-arm64)
    Format Binary           : prisma-fmt 8d8414deb360336e4698a65aa45a1fbaf1ce13d8 (at ../../node_modules/prisma/node_modules/@prisma/engines/prisma-fmt-darwin-arm64)
    Default Engines Hash    : 8d8414deb360336e4698a65aa45a1fbaf1ce13d8
    Studio                  : 0.469.0
    
    
    bug 
    opened by kittipojsr 4
  • Default Filters for FindMany

    Default Filters for FindMany

    Problem

    Filters for list (find many) are not appear out of the box

    Suggested solution

    Have default optional filters like Hasura where we can filters based on other fields (columns) and it should be as powerful like having equal, greater than, lesser than and like.

    opened by ibrahimyaacob92 4
  • generated schemas issue

    generated schemas issue

    Bug description

    Hi,

    I have a problem getting implicit many-to-many relations to work with the generated code. Attached you find my schema and client-code.

    Problem is, VSCode and Angular Live Deployment Server both show the same TypeScript error, related to the generated type:

    error TS2739: Type '{ create: { id: number; name: string; }[]; }' is missing the following properties from type '{ connect: { id: number; } | { id: number; }[]; create: { name: string; } | { name: string; id: number; } | { name: string; }[] | { name: string; id: number; }[]; connectOrCreate: { create: { name: string; } | { ...; }; where: { ...; }; } | { ...; }[]; }': connect, connectOrCreate
    
    53             tags: {
                   ~~~~
    
      ./prisma/trpc/schemas/objects/ProjectUncheckedCreateWithoutAuthorInput.schema.ts:12:3
        12   tags: z.object(TagUncheckedCreateNestedManyWithoutProjectsInputSchemaObject),
             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        The expected type comes from property 'tags' which is declared here on type '{ id: number; tags: { connect: { id: number; } | { id: number; }[]; create: { name: string; } | { name: string; id: number; } | { name: string; }[] | { name: string; id: number; }[]; connectOrCreate: { create: { name: string; } | { ...; }; where: { ...; }; } | { ...; }[]; }; ... 4 more ...; desc: string; }'
    

    So the type needs all of create, connect & createOnConnect methods ?!

    Or am I doing something else wrong ? With plain prisma the same query is working perfectly.

    How to reproduce

    use my schema, the generator & my client code

    Expected behavior

    Type should work with create method only

    Prisma information

    schema:

    model User {
      id        Int       @id @default(autoincrement())
      createdAt DateTime  @default(now())
      email     String    @unique
      name      String?
      password  String?
      projects  Project[]
    }
    
    model Project {
      id        Int              @id @default(autoincrement())
      createdAt DateTime         @default(now())
      published Boolean          @default(false)
      title     String
      shortDesc String
      desc      String
      author    User             @relation(fields: [authorId], references: [id])
      authorId  Int
      tags      Tag[]
    }
    
    model Tag {
      id       Int              @id @default(autoincrement())
      name     String
      projects Project[]
    }
    

    client-code:

    trcp.mutation('user.createOneUser', {
      data: {
        email: '[email protected]',
        name: 'Fabian Dreßen',
        projects: {
          create: [{
            title: 'Sample project  ',
            shortDesc: 'BlaBla Blub',
            desc: 'adasdasd dasdasdasd',
            tags: {
              create: [
                { name: 'sometag' },
                { name: 'anothertag' },
              ],
            }
          }],
        }
      }
    });
    

    Environment & setup

    • OS: Ubuntu
    • Database: SQLite
    • Node.js version: v14.18.1

    Prisma Version

    prisma                  : 3.14.0
    @prisma/client          : 3.14.0
    Current platform        : debian-openssl-1.1.x
    Query Engine (Node-API) : libquery-engine 2b0c12756921c891fec4f68d9444e18c7d5d4a6a (at node_modules/@prisma/engines/libquery_engine-debian-openssl-1.1.x.so.node)
    Migration Engine        : migration-engine-cli 2b0c12756921c891fec4f68d9444e18c7d5d4a6a (at node_modules/@prisma/engines/migration-engine-debian-openssl-1.1.x)
    Introspection Engine    : introspection-core 2b0c12756921c891fec4f68d9444e18c7d5d4a6a (at node_modules/@prisma/engines/introspection-engine-debian-openssl-1.1.x)
    Format Binary           : prisma-fmt 2b0c12756921c891fec4f68d9444e18c7d5d4a6a (at node_modules/@prisma/engines/prisma-fmt-debian-openssl-1.1.x)
    Default Engines Hash    : 2b0c12756921c891fec4f68d9444e18c7d5d4a6a
    Studio                  : 0.460.0
    
    bug 
    opened by brainwind-software 4
  • Router generation fails on

    Router generation fails on "...OrThrow" queries

    Bug description

    Since updating to version 0.6.0, my route generation fails on all "OrThrow" queries. The generated Router has on all of those queries an undefined procedure name and an undefined input:

    Bildschirm­foto 2022-11-12 um 13 40 21

    How to reproduce

    1. Run Prisma generate
    2. Look at the generated Router files

    Expected behavior

    The generated Procedure should be either "Mutation" or "Query" and the input should not be "undefined".

    Prisma information

    datasource db {
      provider = "postgresql"
      url      = env("DATABASE_URL")
    }
    
    generator client {
      provider = "prisma-client-js"
    }
    
    generator trpc {
      provider       = "prisma-trpc-generator"
      withMiddleware = false
      withShield     = true
      contextPath    = "../../../../context"
      isGenerateSelect   = true
      isGenerateInclude  = true
    }
    
    model User {
      id                Int                 @id @default(autoincrement())
      email             String              @unique
      password          String
      name              String
      messages          Message[]
      tokens            Token[]
      ownedChats        Chat[]              @relation("Owner")
      chats             Chat[]
      EmailConfirmation EmailConfirmation[]
    }
    
    model Message {
      id        Int      @id @default(autoincrement())
      createdAt DateTime
      createdBy User     @relation(fields: [creatorId], references: [id])
      creatorId Int
      chat      Chat     @relation(fields: [chatId], references: [id])
      chatId    Int
      content   String
    }
    
    model Chat {
      id        Int       @id @default(autoincrement())
      title     String
      createdAt DateTime
      creatorId Int
      creator   User      @relation(name: "Owner", fields: [creatorId], references: [id])
      users     User[]
      messages  Message[]
    }
    
    model Token {
      id        Int      @id @default(autoincrement())
      createdAt DateTime
      token     String   @unique
      user      User     @relation(fields: [userId], references: [id])
      userId    Int
      lifetime  Int
    }
    
    model EmailConfirmation {
      id        Int      @id @default(autoincrement())
      createdAt DateTime
      token     String   @unique
      user      User     @relation(fields: [userId], references: [id])
      userId    Int
      lifetime  Int
    }
    
    

    Environment & setup

    OS: MacOS Database: PostgreSQL Node.js Version: 18.11.0

    Prisma Version

    prisma                  : 4.6.1
    @prisma/client          : 4.6.1
    Current platform        : darwin-arm64
    Query Engine (Node-API) : libquery-engine 694eea289a8462c80264df36757e4fdc129b1b32 (at node_modules/@prisma/engines/libquery_engine-darwin-arm64.dylib.node)
    Migration Engine        : migration-engine-cli 694eea289a8462c80264df36757e4fdc129b1b32 (at node_modules/@prisma/engines/migration-engine-darwin-arm64)
    Introspection Engine    : introspection-core 694eea289a8462c80264df36757e4fdc129b1b32 (at node_modules/@prisma/engines/introspection-engine-darwin-arm64)
    Format Binary           : prisma-fmt 694eea289a8462c80264df36757e4fdc129b1b32 (at node_modules/@prisma/engines/prisma-fmt-darwin-arm64)
    Format Wasm             : @prisma/prisma-fmt-wasm 4.6.1-3.694eea289a8462c80264df36757e4fdc129b1b32
    Default Engines Hash    : 694eea289a8462c80264df36757e4fdc129b1b32
    Studio                  : 0.476.0
    
    bug 
    opened by fleischerdesign 3
  • Support for Prisma 4.x

    Support for Prisma 4.x

    Problem

    Many thanks for providing this awesome package. I have been using it for some time with Prisma 3.15.2.

    As it seems, upgrading to Prisma 4.0.0 results in an error when running npx prisma generate with this package installed.

    What is needed to support Prisma 4.x and how can we help?

    Alternatives

    Currently, I'm generating the routers and schemas with the Prisma 3.15.2 version and porting it to a new Prisma 4.0.0 project by hand.

    prisma 
    opened by activemonkeys 3
  • Wrong import path

    Wrong import path

    Bug description

    It might just be my machine, but anyways. When running npx prisma generate I have the issue that the trpc-generator (with trpc-shield) makes an invalid include in routers/helpers/createRouter.ts. The line that is outputted will use \ as separators which I believe causes an issue where my import for example will look like: import { permissions } from "X:\Gamer 2\test-npm\prisma/shield/shield" when a path with \\ is expected.

    How to reproduce

    1. Create a simple test project with a prisma client and trcp-shield
    2. Enable withShield in your prisma schema
    3. Run 'npx prisma generate'
    4. Check the file routers/helpers/createRouter.ts in your generated folder
    5. See that in the import it will have used single back slash instead of double back slash

    Expected behavior

    The import path should include the correct path to shield permissions

    Prisma information

    generator client {
        provider = "prisma-client-js"
    }
    
    generator trpc {
        provider = "prisma-trpc-generator"
        output   = "./trpc"
    	withMiddleware = true
    	withShield     = true
    	contextPath    = "../../../../src/context"
    }
    
    datasource db {
        provider = "mysql"
        url      = env("DATABASE_URL")
    }
    
    model User {
        id        Int      @id @default(autoincrement())
        email     String   @unique(map: "email")
        password  String
        name      String
        rank      Rank
        createdAt DateTime @default(now())
        updatedAt DateTime @updatedAt
    }
    
    enum Rank {
        Admin
        Moderator
        User
    }
    

    Environment & setup

    • OS: Windows 10 Home
    • Database: MySQL
    • Node.js version: 16.14.2

    Prisma Version

    Environment variables loaded from .env
    prisma                  : 4.3.1
    @prisma/client          : 4.3.1
    Current platform        : windows
    Query Engine (Node-API) : libquery-engine c875e43600dfe042452e0b868f7a48b817b9640b (at node_modules\@prisma\engines\query_engine-windows.dll.node)
    Migration Engine        : migration-engine-cli c875e43600dfe042452e0b868f7a48b817b9640b (at node_modules\@prisma\engines\migration-engine-windows.exe)
    Introspection Engine    : introspection-core c875e43600dfe042452e0b868f7a48b817b9640b (at node_modules\@prisma\engines\introspection-engine-windows.exe)
    Format Binary           : prisma-fmt c875e43600dfe042452e0b868f7a48b817b9640b (at node_modules\@prisma\engines\prisma-fmt-windows.exe)
    Format Wasm             : @prisma/prisma-fmt-wasm 4.3.0-32.c875e43600dfe042452e0b868f7a48b817b9640b
    Default Engines Hash    : c875e43600dfe042452e0b868f7a48b817b9640b
    Studio                  : 0.473.0
    
    bug 
    opened by aske02 2
  • More granual generator options

    More granual generator options

    Problem

    There are a number of the routers and schemas generated that aren't always needed. For example, we only need a findUniqueAccount schema for our Account router, as all the other crud actions aren't necessary for our specific usecase. It'd be good to be able to specify, per model, what routes and schemas need to be generated. I know it's not 100% necessary, as you can just pick out the bits you need and leave the rest, but it'd be nice to generate a more concise, specific selection of routers and schemas so that each time you don't have to pick through the unnecessary bits

    Suggested solution

    I'm not particularly well versed on the Prisma schema syntax and how it interacts with generators. In an ideal work something like

    {
          modelName: {
                 createOne: true,
                 createMany: false,
                 findUnique: true,
                 ....
          }
    }
    

    would be ideal. However, just at a glance I doubt prisma's schema will allow json objects. I'm not sure if you can even do nesting, something like a YAML like synax could work if that's possible like

    modelName:
          createdOne: true
          createMany: false
          findUnique: true
    

    Alternatives

    Beyond the above, I'm not sure, I hope this could be of at least some help in seeing the potential helpfulness of this feature and how it may be implementing, if it's even possible

    Additional context

    enhancement 
    opened by callum-gander 1
  • Support date strings

    Support date strings

    Problem

    payload {
          data: {
            name: 'Blanca Hyatt',
            createdAt: 2022-08-09T03:58:40.668Z,
            updatedAt: 2022-08-08T18:58:18.021Z
          }
        }
    
    result [
          {
            code: 'invalid_type',
            expected: 'date',
            received: 'string',
            path: [ 'data', 'createdAt' ],
            message: 'Expected date, received string'
          },
          {
            code: 'invalid_type',
            expected: 'date',
            received: 'string',
            path: [ 'data', 'updatedAt' ],
            message: 'Expected date, received string'
          }
        ]
    

    Suggested solution

    const dateSchema = z.preprocess((arg) => {
      if (typeof arg == "string" || arg instanceof Date) return new Date(arg);
    }, z.date());
    type DateSchema = z.infer<typeof dateSchema>;
    // type DateSchema = Date
    
    dateSchema.safeParse(new Date("1/12/22")); // success: true
    dateSchema.safeParse("2022-01-12T00:00:00.000Z"); // success: true
    

    Alternatives

    new Date('2022-08-09T03:58:40.668Z');
    

    Additional context

    Taken from this issue: https://github.com/omar-dulaimi/prisma-trpc-generator/issues/22

    enhancement 
    opened by omar-dulaimi 0
  • Extend zod schema with prisma.schema comments

    Extend zod schema with prisma.schema comments

    Problem

    Since Prisma does not have such a reach check as Zod has - like min/max/length, email/URL, transform, etc. - we could add those extra Zod checks using Prisma comments ///

    prisma.schema

    model Post {
      id String @id @default(uuid()) /// @zod.uuid()
    
      /// @zod.max(255, { message: "The title must be shorter than 256 characters" })
      title String
    
      contents String /// @zod.max(10240)
    }
    

    zod schema output

    export const PostModel = z.object({
    	id: z.string().uuid(),
    	title: z.string().max(255, { message: 'The title must be shorter than 256 characters' }),
    	contents: z.string().max(10240),
    })
    

    Suggested solution

    here's an example in a similar prisma2zod generator

    Just a suggestions

    Maybe you can optionally provide an npm package, that generates tRPC based on zod schema from another plugin(s).

    Or maybe in generator configuration, we can add pre- and post-processors to be triggered during prisma.schema generation to do some extra stuff.

    enhancement 
    opened by olehmelnyk 2
Releases(1.0.2)
  • 1.0.2(Jan 1, 2023)

  • 1.0.1(Jan 1, 2023)

  • 1.0.0(Dec 31, 2022)

    What's Changed

    • Pass contextpath to prisma-trpc-shield-generator by @omar-dulaimi in https://github.com/omar-dulaimi/prisma-trpc-generator/pull/58

    Full Changelog: https://github.com/omar-dulaimi/prisma-trpc-generator/compare/0.9.1...1.0.0

    Source code(tar.gz)
    Source code(zip)
  • 0.9.1(Dec 31, 2022)

    What's Changed

    • Fix invalid types for the "groupBy" function by @Shahidul1004 in https://github.com/omar-dulaimi/prisma-trpc-generator/pull/51

    Full Changelog: https://github.com/omar-dulaimi/prisma-trpc-generator/compare/0.9.0...0.9.1

    Source code(tar.gz)
    Source code(zip)
  • 0.9.0(Dec 30, 2022)

    What's Changed

    • Implement setting tRPC instance options by @omar-dulaimi in https://github.com/omar-dulaimi/prisma-trpc-generator/pull/56

    Full Changelog: https://github.com/omar-dulaimi/prisma-trpc-generator/compare/0.8.2...0.9.0

    Source code(tar.gz)
    Source code(zip)
  • 0.8.2(Dec 30, 2022)

    What's Changed

    • Update all project dependencies by @omar-dulaimi in https://github.com/omar-dulaimi/prisma-trpc-generator/pull/55

    Full Changelog: https://github.com/omar-dulaimi/prisma-trpc-generator/compare/0.8.1...0.8.2

    Source code(tar.gz)
    Source code(zip)
  • 0.8.1(Dec 25, 2022)

  • 0.8.0(Dec 25, 2022)

    What's Changed

    • tRPC 10 Support by @mwarger in https://github.com/omar-dulaimi/prisma-trpc-generator/pull/53

    New Contributors

    • @mwarger made their first contribution in https://github.com/omar-dulaimi/prisma-trpc-generator/pull/53

    Full Changelog: https://github.com/omar-dulaimi/prisma-trpc-generator/compare/0.7.2...0.8.0

    Source code(tar.gz)
    Source code(zip)
  • 0.7.2(Dec 2, 2022)

  • 0.7.1(Dec 2, 2022)

  • 0.7.0(Nov 28, 2022)

    What's Changed

    • Exclude-models-and-related-fields by @omar-dulaimi in https://github.com/omar-dulaimi/prisma-trpc-generator/pull/45

    Full Changelog: https://github.com/omar-dulaimi/prisma-trpc-generator/compare/0.6.1...0.7.0

    Source code(tar.gz)
    Source code(zip)
  • 0.6.1(Nov 17, 2022)

    What's Changed

    • suppress 'OrThrow' when matching opType by @kristinlindquist in https://github.com/omar-dulaimi/prisma-trpc-generator/pull/43

    New Contributors

    • @kristinlindquist made their first contribution in https://github.com/omar-dulaimi/prisma-trpc-generator/pull/43

    Full Changelog: https://github.com/omar-dulaimi/prisma-trpc-generator/compare/0.6.0...0.6.1

    Source code(tar.gz)
    Source code(zip)
  • 0.6.0(Nov 12, 2022)

    What's Changed

    • integrate-select-and-include-support by @Shahidul1004 in https://github.com/omar-dulaimi/prisma-trpc-generator/pull/41

    New Contributors

    • @Shahidul1004 made their first contribution in https://github.com/omar-dulaimi/prisma-trpc-generator/pull/41

    Full Changelog: https://github.com/omar-dulaimi/prisma-trpc-generator/compare/0.5.0...0.6.0

    Source code(tar.gz)
    Source code(zip)
  • 0.5.0(Nov 4, 2022)

  • 0.4.5(Nov 4, 2022)

    • Updates Prisma Zod Generator to latest version, which fixes the missing Aggregate fields bug

    Full Changelog: https://github.com/omar-dulaimi/prisma-trpc-generator/compare/0.4.4...0.4.5

    Source code(tar.gz)
    Source code(zip)
  • 0.4.4(Sep 19, 2022)

    What's Changed

    • fix permissions import path by @omar-dulaimi in https://github.com/omar-dulaimi/prisma-trpc-generator/pull/35

    Full Changelog: https://github.com/omar-dulaimi/prisma-trpc-generator/compare/0.4.3...0.4.4

    Source code(tar.gz)
    Source code(zip)
  • 0.4.3(Sep 5, 2022)

    What's Changed

    • Fix-generating-mongodb-raw-queries by @omar-dulaimi in https://github.com/omar-dulaimi/prisma-trpc-generator/pull/31

    Full Changelog: https://github.com/omar-dulaimi/prisma-trpc-generator/compare/0.4.2...0.4.3

    Source code(tar.gz)
    Source code(zip)
  • 0.4.2(Sep 4, 2022)

  • 0.4.1(Aug 11, 2022)

    What's Changed

    • update zod generator by @omar-dulaimi in https://github.com/omar-dulaimi/prisma-trpc-generator/pull/26

    Full Changelog: https://github.com/omar-dulaimi/prisma-trpc-generator/compare/0.4.0...0.4.1

    Source code(tar.gz)
    Source code(zip)
  • 0.4.0(Jul 20, 2022)

    What's Changed

    • Respect-prisma-client-output-path by @omar-dulaimi in https://github.com/omar-dulaimi/prisma-trpc-generator/pull/20

    Full Changelog: https://github.com/omar-dulaimi/prisma-trpc-generator/compare/0.3.1...0.4.0

    Source code(tar.gz)
    Source code(zip)
  • 0.3.1(Jul 16, 2022)

    What's Changed

    • Fix-create-many-mutation-input by @omar-dulaimi in https://github.com/omar-dulaimi/prisma-trpc-generator/pull/16

    Full Changelog: https://github.com/omar-dulaimi/prisma-trpc-generator/compare/0.3.0...0.3.1

    Source code(tar.gz)
    Source code(zip)
  • 0.3.0(Jul 15, 2022)

    What's Changed

    • Add-option-to-specify-context-path by @omar-dulaimi in https://github.com/omar-dulaimi/prisma-trpc-generator/pull/12

    Full Changelog: https://github.com/omar-dulaimi/prisma-trpc-generator/compare/0.2.1...0.3.0

    Source code(tar.gz)
    Source code(zip)
  • 0.2.1(Jul 13, 2022)

    What's Changed

    • Fix-model-name-casing by @omar-dulaimi in https://github.com/omar-dulaimi/prisma-trpc-generator/pull/9

    Full Changelog: https://github.com/omar-dulaimi/prisma-trpc-generator/compare/0.2.0...0.2.1

    Source code(tar.gz)
    Source code(zip)
  • 0.2.0(Jul 12, 2022)

    What's Changed

    • Upgrade-to-prisma-4 by @omar-dulaimi in https://github.com/omar-dulaimi/prisma-trpc-generator/pull/7

    Full Changelog: https://github.com/omar-dulaimi/prisma-trpc-generator/commits/0.2.0

    Source code(tar.gz)
    Source code(zip)
Owner
Omar Dulaimi
Full Stack Software Engineer
Omar Dulaimi
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 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
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
A NestJS module that allows you use Prisma, set up multiple Prisma services, and use multi-tenancy in each Prisma service.

NestJS Prisma Module Installation To use this package, first install it: npm i @sabinthedev/nestjs-prisma Basic Usage In order to use this package, yo

Sabin Adams 39 Dec 2, 2022
NX monorepo showing the TMDB Watchlist mobile app with Expo, tRPC, Next, and Prisma

tmdb-watchlist-prisma This app uses TMDB to retrieve a list of Now Playing movies. You can add/remove movies to track which ones you've watched. There

Mat Warger 65 Dec 28, 2022
A fullstack TikTok clone with Nextjs, Prisma, trpc

TikTok Clone A fullstack TikTok clone with Nextjs, Prisma, trpc Live demo Official website: https://toptop-clone.vercel.app/ Main technology used The

Phong Nguyen 115 Dec 19, 2022
Kaol Stack - Prisma, Expo, Next, TRPC, Solito, Tailwind - A monorepo template for a truly universal app

Kaol Stack ?? About A monorepo with Prisma, Next.js, Expo, tRPC, Authentication and Solito setup and configured to work together. With this setup you

Matheus Vicente 187 Dec 21, 2022
Next.js + tRPC + Blitz.js Auth + Prisma. Fullstack app example

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://

Daiki Okumura 6 Oct 12, 2022
Collect and generate mapping from file-based routers

roullector: route collector Collect and generate route data from a file-based router such as svelte-kit's What this does: show / hide <!-- before -->

Quang Phan 4 Apr 9, 2022
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 Generator for Pothos Codegen.

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 o

Emanuel 30 Dec 22, 2022
Fully controllable vanilla-js material design ripple effect generator.

Fully controllable vanilla-js material design ripple effect generator. This can be used with any JavaScript framework and/or any CSS framework. Demo I

71 Dec 16, 2022
End-to-end typesafe APIs with tRPC.io in SvelteKit applications

✨ tRPC-SvelteKit End-to-end typesafe APIs with tRPC.io in SvelteKit applications. No code generation, run-time bloat, or build pipeline. ❤️ ???? See b

Ionut-Cristian Florescu 307 Dec 29, 2022
tRPC-ified SWR hooks

trpc-swr tRPC-ified SWR hooks Installation npm install trpc-swr @trpc/client Usage First, create your fully typed hooks using your router type: // trp

Sachin Raja 129 Jan 8, 2023
Proof of concept: support immutable trpc servers using lambdas to ensure client/server compatibility

auto-versioned-trpc-aws-lambda Proof of concept to support an automatically versioned AWS Lambda running tRPC to ensure a somewhat graceful and automa

Kenneth Skovhus 5 Aug 30, 2022
tRPC test & precursor to a billion dollar social cat network

CatMash What is this? Have you ever wanted to rank 11,000 cat pictures by cuteness? Of course you have. That's what we're doing here. This is an app b

Christopher Ehrlich 6 Dec 18, 2022
OpenAPI support for tRPC 🧩

trpc-openapi OpenAPI support for tRPC ?? Easy REST endpoints for your tRPC procedures. Perfect for incremental adoption. OpenAPI version 3.0.3. Usage

James Berry 841 Jan 9, 2023