Giter VIP home page Giter VIP logo

prisma-yup-generator's Introduction

Prisma Yup Generator

npm version npm HitCount npm

Automatically generate Yup schemas from your Prisma Schema, and use them to validate your API endpoints or any other use you have. Updates every time npx prisma generate runs.

Buy Me A Coffee

Table of Contents

Supported Prisma Versions

Prisma 4

  • 0.2.0 and higher

Prisma 2/3

  • 0.1.5 and lower

Installation

Using npm:

 npm install prisma-yup-generator

Using yarn:

 yarn add prisma-yup-generator

Usage

1- Star this repo 😉

2- Add the generator to your Prisma schema

generator yup {
  provider = "prisma-yup-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 the following files

Yup Schemas

4- Use generated schemas somewhere in your API logic, like middleware or decorator

import { PostCreateOneSchema } from './prisma/generated/schemas';

app.post('/blog', async (req, res, next) => {
  const { body } = req;
  await PostCreateOneSchema.validate(body);
});

Additional Options

Option  Description Type  Default
output Output directory for the generated yup schemas string ./generated

Use additional options in the schema.prisma

generator yup {
  provider   = "prisma-yup-generator"
  output     = "./generated-yup-schemas"
}

prisma-yup-generator's People

Contributors

omar-dulaimi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

prisma-yup-generator's Issues

yup__WEBPACK_IMPORTED_MODULE_0__.link is not a function

Bug description

Follow up of #1: I'm getting the following error during an updateOne validation:

error - (api)/prisma/generated/schemas/objects/NestedStringFilter.schema.ts (18:4) @ eval
TypeError: yup__WEBPACK_IMPORTED_MODULE_0__.link is not a function
  16 |   not: Yup.mixed().oneOfSchemas([
  17 |     Yup.string(),
> 18 |     Yup.link('#NestedStringFilter'),
     |    ^
  19 |   ]),
  20 | }
  21 | 

FYI: I'm using this package in a Next.js Typescript project. Maybe I did something wrong or looked at the wrong places but I did not find any information about the Yup.link function anywhere

How to reproduce

running await QuestUpdateOneSchema.validate({ ...body })

Expected behavior

No response

Prisma information

// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

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

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

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[]
  Quests        Quest[]
}

model VerificationToken {
  identifier String
  token      String   @unique
  expires    DateTime

  @@unique([identifier, token])
}

model Quest {
  id          String  @id @default(uuid())
  name        String?
  description String?
  draft       Boolean @default(true)
  user        User    @relation(fields: [userId], references: [id])
  userId      String
}

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

Environment & setup

OS: macOS 12.2.1
Database: PostgreSQL 13
Node.js version: v16.14.2

Prisma Version

➜ npx prisma -v      
Environment variables loaded from .env
prisma                  : 3.13.0
@prisma/client          : 3.13.0
Current platform        : darwin-arm64
Query Engine (Node-API) : libquery-engine efdf9b1183dddfd4258cd181a72125755215ab7b (at node_modules/@prisma/engines/libquery_engine-darwin-arm64.dylib.node)
Migration Engine        : migration-engine-cli efdf9b1183dddfd4258cd181a72125755215ab7b (at node_modules/@prisma/engines/migration-engine-darwin-arm64)
Introspection Engine    : introspection-core efdf9b1183dddfd4258cd181a72125755215ab7b (at node_modules/@prisma/engines/introspection-engine-darwin-arm64)
Format Binary           : prisma-fmt efdf9b1183dddfd4258cd181a72125755215ab7b (at node_modules/@prisma/engines/prisma-fmt-darwin-arm64)
Default Engines Hash    : efdf9b1183dddfd4258cd181a72125755215ab7b
Studio                  : 0.459.0

create indexes

Problem

It is now needed to target a specific filename to get to a schema.:

import { UserUpdateInputObjectSchema } from '{...}/gen/schemas/objects/UserUpdateInput.schema'

Suggested solution

It would be really awesome if you could generate indexes so that we can just import like this:

import { UserUpdateInputObjectSchema } from `{...}/gen/schemas`

Can't resolve './QueryMode.schema'

Bug description

Thank you for this great generator. Unfortunately, I'm getting the following error during an updateOne validation:

Module not found: Can't resolve './QueryMode.schema'
  2 | import * as Yup from 'yup'
  3 | import '../helpers/oneOfSchemas.helper.ts'
> 4 | import { QueryModeSchemaObject } from './QueryMode.schema'
  5 | import { NestedStringNullableFilterSchemaObject } from './NestedStringNullableFilter.schema'
  6 | 
  7 | export const StringNullableFilterSchemaObject = {

Import trace for requested module:
./prisma/generated/schemas/objects/AccountScalarWhereInput.schema.ts
./prisma/generated/schemas/objects/AccountUpdateManyWithoutUserInput.schema.ts
./prisma/generated/schemas/objects/UserUpdateWithoutQuestsInput.schema.ts
./prisma/generated/schemas/objects/UserUpdateOneRequiredWithoutQuestsInput.schema.ts
./prisma/generated/schemas/objects/QuestUpdateInput.schema.ts
./prisma/generated/schemas/updateOneQuest.schema.ts
./pages/api/quest/[id].ts

While taking a look into StringNullableFilter.schema.ts in prisma/generated/schemas/objects it seems like there is an incorrect import statement:

import { QueryModeSchemaObject } from './QueryMode.schema'

which should be:

import { QueryModeSchemaObject } from '../enums/QueryMode.schema'

How to reproduce

running await QuestUpdateOneSchema.validate({ ...body })

Expected behavior

No response

Prisma information

// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

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

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

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[]
  Quests        Quest[]
}

model VerificationToken {
  identifier String
  token      String   @unique
  expires    DateTime

  @@unique([identifier, token])
}

model Quest {
  id          String  @id @default(uuid())
  name        String?
  description String?
  draft       Boolean @default(true)
  user        User    @relation(fields: [userId], references: [id])
  userId      String
}

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

Environment & setup

  • OS: macOS 12.2.1
  • Database: PostgreSQL 13
  • Node.js version: v16.14.2

Prisma Version

➜ npx prisma version 
Environment variables loaded from .env
prisma                  : 3.13.0
@prisma/client          : 3.13.0
Current platform        : darwin-arm64
Query Engine (Node-API) : libquery-engine efdf9b1183dddfd4258cd181a72125755215ab7b (at node_modules/@prisma/engines/libquery_engine-darwin-arm64.dylib.node)
Migration Engine        : migration-engine-cli efdf9b1183dddfd4258cd181a72125755215ab7b (at node_modules/@prisma/engines/migration-engine-darwin-arm64)
Introspection Engine    : introspection-core efdf9b1183dddfd4258cd181a72125755215ab7b (at node_modules/@prisma/engines/introspection-engine-darwin-arm64)
Format Binary           : prisma-fmt efdf9b1183dddfd4258cd181a72125755215ab7b (at node_modules/@prisma/engines/prisma-fmt-darwin-arm64)
Default Engines Hash    : efdf9b1183dddfd4258cd181a72125755215ab7b
Studio                  : 0.459.0

error - ReferenceError: Cannot access 'AccountWhereInputObjectSchema' before initialization

Bug description

I'm getting the following error with v0.1.4:

error - ReferenceError: Cannot access 'AccountWhereInputObjectSchema' before initialization

How to reproduce

having the following code in the api:

await GameCreateSchema.validate({
    ...body,
    userId,
})

Expected behavior

No response

Prisma information

see #6

Environment & setup

see #6

Prisma Version

prisma                  : 3.15.1
@prisma/client          : 3.15.1
Current platform        : darwin-arm64
Query Engine (Node-API) : libquery-engine 461d6a05159055555eb7dfb337c9fb271cbd4d7e (at node_modules/@prisma/engines/libquery_engine-darwin-arm64.dylib.node)
Migration Engine        : migration-engine-cli 461d6a05159055555eb7dfb337c9fb271cbd4d7e (at node_modules/@prisma/engines/migration-engine-darwin-arm64)
Introspection Engine    : introspection-core 461d6a05159055555eb7dfb337c9fb271cbd4d7e (at node_modules/@prisma/engines/introspection-engine-darwin-arm64)
Format Binary           : prisma-fmt 461d6a05159055555eb7dfb337c9fb271cbd4d7e (at node_modules/@prisma/engines/prisma-fmt-darwin-arm64)
Default Engines Hash    : 461d6a05159055555eb7dfb337c9fb271cbd4d7e
Studio                  : 0.462.0

Upcoming rename of `@prisma/sdk` to `@prisma/internals` with Prisma 4

Hey,

Jan from Prisma Engineering here.

Quick heads up that we will soon rename our @prisma/sdk package to @prisma/internals with Prisma 4, which we plan to release on June 28th (soon!).

The @prisma/sdk package was meant as an Prisma internal package only, but somehow it leaked out over time and is now used across all kinds of tools - including yours of course 😄

With the rename of the Npm package we want to make it clearer that we can not give any API guarantees for @prisma/internals, might need to introduce breaking changes to the API from time to time and will not follow semantic versioning (breaking changes only in major upgrade) with it. We think that it is better communicated with internals than with sdk.
With Prisma 4, besides the package name nothing should change though.

Additionally it would be super helpful if you could help us gain an understanding where, how and why you are using @prisma/sdk (soon @prisma/internals, remember 😀) to achieve, what exactly. We want to cleanup that package and your feedback will be valuable to us to define a better API.

Looking forward to your feedback.

Best
Jan & your friends at Prisma

PS: Are you using Prisma.dmmf from import { Prisma } from '@prisma/client' in your code somewhere by chance? That will also change soon and not include the Prisma.dmmf.schema sub property. Instead you can use getDmmf from @prisma/internals moving forward.

TypeError: Cannot read properties of undefined (reading 'NestedIntNullableFilterObjectSchema') when generating Yup schema

Bug description

I have a working Nextjs setup with Prisma, Typescript, React Hook Form, and Yup - it's a CRM system.

I am using the types from the Prisma Client in my code and have no issues so far. I introduced Yup validation by directly creating a schema (similar to the types generated by Prisma), and then stumbled across this great looking project, and so I installed it as per the instructions. I setup my form with the Yup resolver (which I've successfully used in the past by creating a Yup schema directly) for React Hook Form. I passed in the DonationCreateSchema imported from prisma/generated/schemas which is the default output folder. I am getting the following error when I start the app:

 ⨯ TypeError: Cannot read properties of undefined (reading 'NestedIntNullableFilterObjectSchema')
    at Module.NestedIntNullableFilterObjectSchema (./prisma/generated/schemas/internals.ts:97:159)
    at eval (./prisma/generated/schemas/objects/NestedDecimalNullableWithAggregatesFilter.schema.ts:17:53)
    at (ssr)/./prisma/generated/schemas/objects/NestedDecimalNullableWithAggregatesFilter.schema.ts (D:\Repos\Charity Manager CRM\crm-fullstack\.next\server\app\admin\donations\create\page.js:1546:1)
    at __webpack_require__ (D:\Repos\Charity Manager CRM\crm-fullstack\.next\server\webpack-runtime.js:33:42)
    at eval (./prisma/generated/schemas/internals.ts:144:115)
    at (ssr)/./prisma/generated/schemas/internals.ts (D:\Repos\Charity Manager CRM\crm-fullstack\.next\server\app\admin\donations\create\page.js:556:1)
    at __webpack_require__ (D:\Repos\Charity Manager CRM\crm-fullstack\.next\server\webpack-runtime.js:33:42)
    at eval (./prisma/generated/schemas/findUniqueCustomer.schema.ts:6:68)
    at (ssr)/./prisma/generated/schemas/findUniqueCustomer.schema.ts (D:\Repos\Charity Manager CRM\crm-fullstack\.next\server\app\admin\donations\create\page.js:468:1)
    at __webpack_require__ (D:\Repos\Charity Manager CRM\crm-fullstack\.next\server\webpack-runtime.js:33:42)
    at eval (./prisma/generated/schemas/index.ts:37:84)
    at (ssr)/./prisma/generated/schemas/index.ts (D:\Repos\Charity Manager CRM\crm-fullstack\.next\server\app\admin\donations\create\page.js:545:1)
    at __webpack_require__ (D:\Repos\Charity Manager CRM\crm-fullstack\.next\server\webpack-runtime.js:33:42)
    at eval (./src/components/donation/create/Form.tsx:18:83)
    at (ssr)/./src/components/donation/create/Form.tsx (D:\Repos\Charity Manager CRM\crm-fullstack\.next\server\app\admin\donations\create\page.js:2096:1)
    at __webpack_require__ (D:\Repos\Charity Manager CRM\crm-fullstack\.next\server\webpack-runtime.js:33:42)
    at eval (./src/components/donation/create/index.tsx:8:63)
    at (ssr)/./src/components/donation/create/index.tsx (D:\Repos\Charity Manager CRM\crm-fullstack\.next\server\app\admin\donations\create\page.js:2118:1)
    at __webpack_require__ (D:\Repos\Charity Manager CRM\crm-fullstack\.next\server\webpack-runtime.js:33:42)

image

The code for my form is provided in the How to reproduce - I've simplified the code (removed my components etc and using native HTML elements) - this still gives me the error so I've ruled out my components being an issue.

I'm not asking for help with writing the form, but more to understand what is causing the issue with the generated Yup schemas based on the Prisma schema I have. It's not too different to the example for this repo. Your help would be greatly appreciated.

How to reproduce

You can setup a simple Nextjs Typescript project, install React Hook Form and set up Prisma with the schema I've provided. Then generate the Yup schemas, create a simple form like my code below:

"use client";
import { SubmitHandler, useForm } from "react-hook-form";
import { FC,  } from "react";
import classNames from "classnames";
import { DonationCreateSchema } from "../../../../prisma/generated/schemas";
import { yupResolver } from "@hookform/resolvers/yup";

interface CreateDonationProps {
  className?: string;
}

const CreateDonationForm: FC<CreateDonationProps> = ({
  className,
}) => {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm({
    mode: "onChange",
    resolver: yupResolver(DonationCreateSchema),
  });

  const onSubmit: SubmitHandler<any> = async (data) => {
    console.log("onSubmit", data);
  };

  return (
    <div
      className={classNames(
        "text-sm flex flex-col items-center justify-center mb-4 bg-white shadow-sm ring-1 ring-gray-900/5 sm:rounded-xl",
        className
      )}
      data-testid="donation_create_form"
    >
      <div className="grow flex flex-col py-2 align-middle px-2 w-full">
        <div className="w-full text-center pt-2 text-lg font-bold">
          Create Donation
        </div>
        <hr className="h-px my-2 bg-gray-200 border-0 dark:bg-gray-500" />
        <form
          className="grow flex flex-col py-2 align-middle px-2 w-full gap-5"
          onSubmit={handleSubmit(onSubmit)}
        >
          <>
            <label htmlFor="amount" className="text-green-500">
              Amount
            </label>
            <input
              id="amount"
              type="text"
              {...register("amount", { required: true })}
              required
              className="w-full"
            />
          </>
          {errors ? (
            <p className="text-red-500 p-4">{JSON.stringify(errors)}</p>
          ) : null}
          <button
            type="submit"
            className="w-full p-3 bg-black text-white"
          >
            SUBMIT
          </button>
        </form>
      </div>
    </div>
  );
};

export default CreateDonationForm;

As soon as you start the app you will see the errors I'm getting. This is a client component in my app.

Expected behavior

I'd expect to be able to use the generated Yup schema to validate my form with React Hook Form using the Yup resolver - this could be a Yup resolver issue, however I have also tried calling the validate method on the generated Schema and it gives me the same errors (this method does not rely on the Yup resolver).

Prisma information

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

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

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model Customer {
  id               Int        @id @default(autoincrement())
  firstName       String?     @db.VarChar(255)
  lastName        String?     @db.VarChar(255)
  email            String?    @db.VarChar(255)
  phone            String?    @db.VarChar(255)
  createdAt       DateTime?   @default(now())
  updatedAt       DateTime?   @default(now())
  title            String?    @db.VarChar(255)
  contactEmail    Boolean?    @db.Boolean @default(false)
  contactPhone    Boolean?    @db.Boolean @default(false)
  contactPost     Boolean?    @db.Boolean @default(false)
  contactSms      Boolean?    @db.Boolean @default(false)
  contactWhatsapp Boolean?    @db.Boolean @default(false)
  donations        Donation[]
}

model Donation {
  id         Int       @id @default(autoincrement())
  amount     Decimal?  @db.Decimal(10, 2)
  date       DateTime? @db.Timestamp(6)
  giftAid   Boolean?
  createdAt DateTime? @default(now())
  updatedAt DateTime? @default(now())
  recurring  Boolean? @db.Boolean @default(false)
  customer   Customer @relation(references: [id], fields: [customerId])
  project    Project  @relation(references: [id], fields: [projectId])
  customerId Int
  projectId  Int
}

model Project {
  id             Int        @id @default(autoincrement())
  name           String?    @db.VarChar(255)
  archived       Boolean?
  description    String?    @db.VarChar(255)
  total          Decimal?   @db.Decimal(10, 2)
  startDate     DateTime?  @db.Date
  endDate       DateTime?  @db.Date
  target         Decimal?   @db.Decimal(10, 2)
  createdAt     DateTime?  @db.Timestamp(6)
  updatedAt     DateTime?  @db.Timestamp(6)
  financialYear String?    @db.VarChar(255)
  donations      Donation[]
}

Environment & setup

  • OS: Windows 11
  • Database: PostgreSQL
  • Node.js version: v20.10.0
  • IDE: VSCode

Prisma Version

@prisma/client: 5.10.2
prisma: 5.10.2
@hookform/resolvers: 3.3.4
react-hook-form: 7.48.2

some schemas are not available at compile time somehow and are registered as undefined

Bug description

the culprit is in the oneOfSchemas helper. The test breaks because it was given an array of schemas that were undefined. You can reproduce it with:

Yup.addMethod(Yup.MixedSchema, 'oneOfSchemas', function (schemas: Yup.AnySchema[]) {
  if (schemas.length && schemas[0] === undefined) debugger
  return this.test('one-of-schemas', 'Not all items in ${path} match one of the allowed schemas', (item) =>
    schemas.some((schema) =>
      // uncommenting the next line will make the test run correctly
      // if (schema === undefined) return true
      schema.isValidSync(item, { strict: true }),
    ),
  )
})

How to reproduce

Expected behavior

No response

Prisma information

Environment & setup

  • OS:
  • Database:
  • Node.js version:

Prisma Version


decorator comments to specify validator

Problem

Hi, Prisma only has simple validation for database fields, but Yup/Joi etc allow have richer validators such as email/regex etc. How much work would it be to put the desired validator+args in decorator comments and apply them in the generator to the ones already picked up?

Suggested solution

Example could be:

/// @PrismaYupGen email.nullable
// or 
/// @PrismaYupGen min(1).max(10)

To keep it simple I removed () from validator without args.

Hope to inspire :)

circular deps generated

Bug description

Hi, the generated output circular references blocking bundlers like webpack. It would be very beneficial to solve this so that we can bundle it for web.

How to reproduce

// config.next.js
/* eslint-disable @typescript-eslint/no-var-requires */
const CircularDependencyPlugin = require('circular-dependency-plugin')

module.exports = withTM({
  reactStrictMode: true,
  swcMinify: false,
  future: {
    webpack5: true, // by default, if you customize webpack config, they switch back to version 4.
    // Looks like backward compatibility approach.
  },
  webpack(config) {
    const circularDependencyPlugin = new CircularDependencyPlugin({
      // exclude detection of files based on a RegExp
      exclude: /a\.js|node_modules/,
      // include specific files based on a RegExp
      // include: //,
      // add errors to webpack instead of warnings
      failOnError: true,
      // allow import cycles that include an asyncronous import,
      // e.g. via import(/* webpackMode: "weak" */ './file.js')
      allowAsyncCycles: false,
      // set the current working directory for displaying module paths
      cwd: process.cwd(),
      // `onStart` is called before the cycle detection starts
      onStart({ compilation }) {
        console.log('start detecting webpack modules cycles')
      },
      // `onDetected` is called for each module that is cyclical
      onDetected({ module: webpackModuleRecord, paths, compilation }) {
        console.log('new CD error')
        console.log(paths)
        // `paths` will be an Array of the relative module paths that make up the cycle
        // `module` will be the module record generated by webpack that caused the cycle
        compilation.errors.push(new Error(paths.join(' -> ')))
      },
      // `onEnd` is called before the cycle detection ends
      onEnd({ compilation }) {
        console.log('end detecting webpack modules cycles')
      },
    })
    config.plugins.push(circularDependencyPlugin)
    return config
  },
})

Expected behavior

No circular references to exist. It should be avoidable by following this paradigm that exports everything from one file: https://medium.com/visual-development/how-to-fix-nasty-circular-dependency-issues-once-and-for-all-in-javascript-typescript-a04c987cf0de

Prisma information

// prisma/schema.prisma

datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}

generator client {
provider = "prisma-client-js"
previewFeatures = ["interactiveTransactions"]
}

generator fieldEncryptionMigrations {
provider = "prisma-field-encryption"
output = "./migrations"
}

generator typegraphql {
provider = "typegraphql-prisma"
output = "../node_modules/.cache/type-graphql"
}

generator yup {
provider = "prisma-yup-generator"
output = "../src/prisma/gen"
}

generator erd {
provider = "prisma-erd-generator"
output = "../docs/diagrams/entity-relationship-diagram.svg"
}

enum Role {
ADMIN
USER
}

enum OrgRole {
OWNER
ADMIN
MEMBER
}

enum Tier {
FREE
PRO
ENTERPRISE
}

enum PaymentStatus {
PENDING
PAID
}

model License {
tier Tier
price Int
description String

@@unique([tier])
}

enum InvoicePeriod {
MONTHLY
YEARLY
}

model Account {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
userId String
type String
provider String
providerAccountId String
refresh_token String? @Map("refreshToken") @db.Text
access_token String? @Map("accessToken") @db.Text
expires_at Int? @Map("expiresAt")
token_type String? @Map("tokenType")
scope String?
id_token String? @Map("idToken") @db.Text
session_state String? @Map("sessionState")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
tier Tier @default(FREE) // may be upgraded to PRO then ENTERPRISE
clusters Cluster[]
organisation Organisation?
invoice Invoice[]

@@unique([provider, providerAccountId])
}

model Session {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
userId String
expires DateTime
session_token String @unique @Map("sessionToken")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
}

model User {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
name String?
email String? @unique
emailVerified DateTime?
image String?
phoneNumber String? /// @Encrypted
address String? /// @Encrypted
country String?
state String?
city String? /// @Encrypted
zipCode String? /// @Encrypted
avatarUrl String? /// @Encrypted
company String?

role Role @default(USER)
accounts Account[]
sessions Session[]
userOrgs UserOrg[]
}

model VerificationToken {
identifier String
token String @unique
expires DateTime

@@unique([identifier, token])
}

model UserOrg {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
userId String @Map("user_id")
organisationId String
role OrgRole
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
organisation Organisation @relation(fields: [organisationId], references: [id])

@@id([userId, organisationId])
}

model Invoice {
id String @id @default(uuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
accountId String
price Int // no fractions, will be exactly as paid in EURO at that moment in time
status PaymentStatus
period InvoicePeriod
startDate DateTime
endDate DateTime

account Account @relation(fields: [accountId], references: [id])
}

model Organisation {
id String @id @default(uuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
accountId String @unique
name String @unique
image String?

account Account @relation(fields: [accountId], references: [id])
orgUsers UserOrg[]
}

model Cluster {
id String @id @default(uuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
key String @default(cuid())
accountId String
name String
description String
provider String
kubecfg String?

account Account @relation(fields: [accountId], references: [id])
}

Environment & setup

  • OS: Mac OS
  • Database: PostgreSQL
  • Node.js version: 16.14.2

Prisma Version

3.14.0

don't generate redundant code

Problem

Hi, all your objects/*.schema files contain redundant code. The top definition is always copied to be used in the exported Yup.object({....

Suggested solution

Just export like this:

export const UserUpdateInputObject = ...
...
export const UserUpdateInputObjectSchema = Yup.object(UserUpdateInputObject)

Module not found: Can't resolve './NullableJsonNullValueInput.schema'

Bug description

My application can't resolve NullableJsonNullValueInput.schema which is placed in prisma/generated/schemas/enums

The files that want to require this file are however located in prisma/generated/schemas/objects

How to reproduce

QuestCreateManyRoomInput.schema.ts uses

import { NullableJsonNullValueInputSchemaObject } from './NullableJsonNullValueInput.schema'

Expected behavior

but it should use

import { NullableJsonNullValueInputSchemaObject } from '../enum/NullableJsonNullValueInput.schema'

Prisma information

// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

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

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

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[]
  Games         Game[]
  S3Image       S3Image[]
}

model VerificationToken {
  identifier String
  token      String   @unique
  expires    DateTime

  @@unique([identifier, token])
}

model Game {
  id          String   @id @default(uuid())
  name        String?
  description String?
  draft       Boolean  @default(true)
  user        User     @relation(fields: [userId], references: [id], onDelete: Cascade)
  userId      String
  rooms       Room[]
  createdAt   DateTime @default(now())
  updatedAt   DateTime @default(now())
}

model Room {
  id        String   @id @default(uuid())
  game      Game     @relation(fields: [gameId], references: [id], onDelete: Cascade)
  gameId    String
  createdAt DateTime @default(now())
  updatedAt DateTime @default(now())
  image     S3Image?
  quests    Quest[]
}

model S3Image {
  id        String   @id @default(uuid())
  user      User     @relation(fields: [userId], references: [id])
  userId    String
  url       String
  createdAt DateTime @default(now())
  updatedAt DateTime @default(now())
  room      Room     @relation(fields: [roomId], references: [id], onDelete: Cascade)
  roomId    String   @unique
}

model Quest {
  id        String     @id @default(uuid())
  createdAt DateTime   @default(now())
  updatedAt DateTime   @default(now())
  room      Room       @relation(fields: [roomId], references: [id], onDelete: Cascade)
  roomId    String
  x         Float
  y         Float
  type      QuestType?
  data      Json?      @default(dbgenerated())
}

enum QuestType {
  QUEST_CRYPTO
  QUEST_CODING
  QUEST_QR_SCAN
  QUEST_STATISTICS
  MEDIA_TEXT
  MEDIA_IMAGE
  MEDIA_INSTAGRAM
  MEDIA_YOUTUBE
  MEDIA_IFRAME
}

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

Environment & setup

  • OS: macOS 12.2.1
  • Database: PostgreSQL 13
  • Node.js version: v16.14.2

Prisma Version

prisma                  : 3.14.0
@prisma/client          : 3.14.0
Current platform        : darwin-arm64
Query Engine (Node-API) : libquery-engine 2b0c12756921c891fec4f68d9444e18c7d5d4a6a (at node_modules/@prisma/engines/libquery_engine-darwin-arm64.dylib.node)
Migration Engine        : migration-engine-cli 2b0c12756921c891fec4f68d9444e18c7d5d4a6a (at node_modules/@prisma/engines/migration-engine-darwin-arm64)
Introspection Engine    : introspection-core 2b0c12756921c891fec4f68d9444e18c7d5d4a6a (at node_modules/@prisma/engines/introspection-engine-darwin-arm64)
Format Binary           : prisma-fmt 2b0c12756921c891fec4f68d9444e18c7d5d4a6a (at node_modules/@prisma/engines/prisma-fmt-darwin-arm64)
Default Engines Hash    : 2b0c12756921c891fec4f68d9444e18c7d5d4a6a
Studio                  : 0.460.0

Fix for "// @ts-nocheck"

Bug description

// @ts-nocheck suppresses errors

oneOfSchemas.helper.ts

import * as Yup from "yup";
declare module "yup" {
  interface MixedSchema {
    oneOfSchemas(schemas: Array<Yup.Schema<any>>): this;
  }
}
Yup.addMethod<Yup.MixedSchema>(
  Yup.mixed,
  "oneOfSchemas",
  function (schemas: Array<Yup.Schema<any>>) {
    return this.test(
      "one-of-schemas",
      "Not all items in [object Object] match one of the allowed schemas",
      (item) =>
        schemas.some((schema) =>
          schema.isValidSync(item, {
            strict: true,
          })
        )
    );
  }
);

How to reproduce

Not applicable

Expected behavior

No response

Prisma information

Not Applicable

Environment & setup

  • All

Prisma Version

Not Applicable

Option to enable force overwrite

Problem

Generator fails with existing files.

Suggested solution

Generator should overwrite generated files or have an option to enable force overwrite.

Alternatives

none

Additional context

Just running generator multiple times.

P.S. Thanks for excellent work, output is clean, up-to standard!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.