Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(zod): support @default for BigInt values #1486

Merged
merged 1 commit into from
Jun 7, 2024

Conversation

aloisklink
Copy link
Contributor

@aloisklink aloisklink commented Jun 6, 2024

Zod schemas fail to generate when using a BigInt type and a @default field, since the generated Zod .schema.ts files use a number literal instead of a BigInt for the default value.

Example

Currently, a ZenStack schema like:

model Post {
  viewMilliseconds BigInt @default(0)
}

would get converted to the following, which throws a TypeScript error

const baseSchema = z.object({
    // Argument of type 'number' is not assignable to parameter of type 'bigint'.
    viewMilliseconds: z.bigint().default(0)
});

Now, it would instead be converted to:

const baseSchema = z.object({
    // we're not using .default(0n) since that syntax only works if
    // TypeScript is setup to target ES2020 or later
    viewMilliseconds: z.bigint().default(BigInt("0"))
});

Failing test

user@pc:~/zenstack/tests/integration (dev)$ pnpm exec jest plugins/zod.test.ts
<---SNIP---->
  ● Zod plugin tests › basic generation

    Command failed: npx zenstack generate --no-version-check --no-dependency-check
    WARNING: Multiple versions of Zenstack packages detected. Run "zenstack info" to see details.
    - Generating Prisma schema
    ✔ Generating Prisma schema
    - Generating PrismaClient enhancer
    ✔ Generating PrismaClient enhancer
    - Generating Zod schemas
    ✔ Generating Zod schemas
    Error compiling generated code:
    node_modules/.zenstack/zod/models/Post.schema.ts:9:35 - error TS2769: No overload matches this call.
      Overload 1 of 2, '(def: bigint): ZodDefault<ZodBigInt>', gave the following error.
        Argument of type 'number' is not assignable to parameter of type 'bigint'.
      Overload 2 of 2, '(def: () => bigint): ZodDefault<ZodBigInt>', gave the following error.
        Argument of type 'number' is not assignable to parameter of type '() => bigint'.

    9     viewCount: z.bigint().default(0),
                                        ~

    node_modules/.zenstack/zod/models/Post.schema.ts:50:32 - error TS2769: No overload matches this call.
      Overload 1 of 2, '(def: bigint): ZodDefault<ZodBigInt>', gave the following error.
        Argument of type 'number' is not assignable to parameter of type 'bigint'.
      Overload 2 of 2, '(def: () => bigint): ZodDefault<ZodBigInt>', gave the following error.
        Argument of type 'number' is not assignable to parameter of type '() => bigint'.

    50  viewCount: z.bigint().default(0)
                                      ~


    : Error compiling generated code

      45 | export function run(cmd: string, env?: Record<string, string>, cwd?: string) {
      46 |     try {
    > 47 |         execSync(cmd, {
         |                 ^
      48 |             stdio: 'pipe',
      49 |             encoding: 'utf-8',
      50 |             env: { ...process.env, DO_NOT_TRACK: '1', ...env },

      at run (../../packages/testtools/src/schema.ts:47:17)
      at ../../packages/testtools/src/schema.ts:233:9
      at ../../packages/testtools/dist/schema.js:31:71
      at Object.<anonymous>.__awaiter (../../packages/testtools/dist/schema.js:27:12)
      at loadSchema (../../packages/testtools/dist/schema.js:149:12)
      at Object.<anonymous> (tests/plugins/zod.test.ts:22:48)

Zod schemas fail to generate when using a `BigInt` type and
a `@default` field, since generated Zod files use a `number` literal
instead of a `BigInt` literal for the default value.
Copy link
Contributor

coderabbitai bot commented Jun 6, 2024

Walkthrough

Walkthrough

The recent changes to the schema-gen.ts file and related tests introduce a new way of handling default values for fields of type 'BigInt'. Specifically, the makeFieldSchema function now assigns default values to 'BigInt' fields using the BigInt notation. Correspondingly, the Zod plugin tests have been updated to include a new 'BigInt' field, viewMilliseconds, with a default value of 0, ensuring that the new functionality is thoroughly tested.

Changes

Files/Paths Change Summary
packages/schema/src/plugins/zod/utils/schema-gen.ts Updated makeFieldSchema function to handle 'BigInt' default values using BigInt notation.
tests/integration/tests/plugins/zod.test.ts Added viewMilliseconds field of type BigInt with default 0 and updated tests for creation and update validations.

Sequence Diagram(s) (Beta)

sequenceDiagram
    participant User
    participant SchemaGen
    participant ZodPluginTest

    User->>SchemaGen: Call makeFieldSchema with BigInt field
    SchemaGen->>SchemaGen: Check field type
    alt Field type is BigInt
        SchemaGen->>SchemaGen: Set default using BigInt notation
    else Field type is not BigInt
        SchemaGen->>SchemaGen: Set default normally
    end
    SchemaGen-->>User: Return schema

    User->>ZodPluginTest: Run tests with new BigInt field
    ZodPluginTest->>ZodPluginTest: Validate creation and update schemas
    ZodPluginTest-->>User: Test results
Loading

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Outside diff range and nitpick comments (1)
packages/schema/src/plugins/zod/utils/schema-gen.ts (1)

155-161: The changes correctly address the issue with BigInt default values by using the BigInt constructor. This is a good approach as it avoids the need for ES2020.

Consider adding a comment explaining why the BigInt constructor is used instead of the n notation for better clarity.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 714220e and 3eab438.

Files selected for processing (2)
  • packages/schema/src/plugins/zod/utils/schema-gen.ts (1 hunks)
  • tests/integration/tests/plugins/zod.test.ts (2 hunks)

tests/integration/tests/plugins/zod.test.ts Show resolved Hide resolved
@ymc9
Copy link
Member

ymc9 commented Jun 7, 2024

Thank you for making the fix @aloisklink ! The change looks great. I'm merging it and will include it in the upcoming v2.2 release.

@ymc9 ymc9 merged commit ba636c8 into zenstackhq:dev Jun 7, 2024
13 checks passed
@aloisklink aloisklink deleted the fix-zod-schema-default-bigint branch June 7, 2024 06:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants