Skip to content

CODEGEN-334 - Throw custom NoTypeDefinitionsFound if no document found whilst loading documents #7093

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

Merged

Conversation

eddeee888
Copy link
Contributor

Description

GraphQL Code Generator uses @graphql-tool/load to load documents.
When there are no documents found given a pattern, @graphql-tool/load throws an error. However, Codegen doesn't know if it's a syntax error, no document found error or anything else.

This PR adds and exports a custom error NoDocumentFoundError to @graphql-tool/load to allow libraries like Codegen to handle No Document Found error case more explicitly

Related Codegen issue dotansimha/graphql-code-generator#9172

Type of change

Please delete options that are not relevant.

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as
    expected)
  • This change requires a documentation update

How Has This Been Tested?

  • Unit test
  • I will use an alpha version to test the Codegen integration

Copy link

changeset-bot bot commented Apr 7, 2025

🦋 Changeset detected

Latest commit: 809bc08

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 2 packages
Name Type
@graphql-tools/load Minor
@graphql-tools/node-require Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Copy link
Contributor

coderabbitai bot commented Apr 7, 2025

📝 Walkthrough

Summary by CodeRabbit

  • New Features
    • Enhanced error handling for missing GraphQL type definitions. When type definitions cannot be located, users now receive a more specific and descriptive error message, improving troubleshooting and integration with related tooling.

Summary by CodeRabbit

  • New Features
    • Introduced a specific error type, NoTypeDefinitionsFound, to enhance error handling when GraphQL type definitions are not found.
  • Tests
    • Updated test cases to utilize modern asynchronous error handling, ensuring accurate detection and reporting of error conditions.

Walkthrough

This update introduces a new error handling mechanism in the GraphQL tools with the NoTypeDefinitionsFound error, which replaces the previous standard Error when type definitions cannot be found. A custom error class is defined to provide more specific error messages, and the tests have been updated to adopt modern asynchronous error handling practices, directly asserting the behavior of the new error.

Changes

File(s) Change Summary
.changeset/soft-stars-pay.md Documents the introduction of the NoTypeDefinitionsFound error in GraphQL tools' error handling.
packages/load/.../load-typedefs.ts Adds the NoTypeDefinitionsFound class extending Error and updates prepareResult to throw this custom error when no valid sources are found.
packages/load/.../documents-from-glob.spec.ts Updates tests to assert promise rejection with NoTypeDefinitionsFound instead of using try-catch blocks for asynchronous error handling.

Sequence Diagram(s)

sequenceDiagram
    participant Loader as GraphQLLoader
    participant PR as prepareResult
    participant Caller as Test/Client

    Caller->>Loader: Request type definitions load
    Loader->>PR: Invoke prepareResult with pointers
    alt Valid type definitions found
        PR-->>Loader: Return type definitions data
        Loader-->>Caller: Deliver type definitions data
    else No type definitions found
        PR-->>Loader: Throw NoTypeDefinitionsFound
        Loader-->>Caller: Propagate NoTypeDefinitionsFound
    end
Loading

Poem

I'm a little rabbit in a code-filled glen,
Hopping through changes again and again.
With "NoTypeDefinitionsFound" lighting the way,
No generic mishaps to ruin the day!
My whiskers twitch with digital delight 🥕,
Cheering for clear errors shining bright!

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

packages/load/src/load-typedefs.ts

Oops! Something went wrong! :(

ESLint: 9.24.0

ESLint couldn't find an eslint.config.(js|mjs|cjs) file.

From ESLint v9.0.0, the default configuration file is now eslint.config.js.
If you are using a .eslintrc.* file, please follow the migration guide
to update your configuration file to the new format:

https://eslint.org/docs/latest/use/configure/migration-guide

If you still have problems after following the migration guide, please stop by
https://eslint.org/chat/help to chat with the team.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 95258f5 and 809bc08.

📒 Files selected for processing (2)
  • .changeset/soft-stars-pay.md (1 hunks)
  • packages/load/src/load-typedefs.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • .changeset/soft-stars-pay.md
  • packages/load/src/load-typedefs.ts
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: Unit Test on Node 18 (windows-latest) and GraphQL v16
  • GitHub Check: Unit Test on Node 23 (ubuntu-latest) and GraphQL v15
  • GitHub Check: Unit Test on Node 22 (ubuntu-latest) and GraphQL v15
  • GitHub Check: Unit Test on Node 18 (ubuntu-latest) and GraphQL v16
  • GitHub Check: Unit Test on Node 18 (ubuntu-latest) and GraphQL v15

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @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 using 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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration 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.

@@ -0,0 +1,8 @@
---
'@graphql-tools/load': minor
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This feels like a minor, rather than a patch because it's not a bug per se
It's could be a major if consumers specifically check Error case 🤔

Happy to be swayed either way here

Copy link
Owner

Choose a reason for hiding this comment

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

It is still Error right? So it should be good imo.

await load(glob, {
loaders: [new GraphQLFileLoader()],
});
expect(true).toBeFalsy();
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Not only related to this test but I found expect(true).toBeFalsy(); will actually throw an error, which will satisfy the expect(e).toBeDefined(); statement below
i.e. the tests in this file will always pass 😅

@@ -135,7 +135,7 @@ function prepareResult({
const pointerList = Object.keys(pointerOptionMap);

if (pointerList.length > 0 && validSources.length === 0) {
throw new Error(`
throw new NoDocumentFoundError(`
Unable to find any GraphQL type definitions for the following pointers:
Copy link
Owner

Choose a reason for hiding this comment

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

Let's move this message inside the new error then. And the constructor can take pointerList.

Copy link
Contributor Author

@eddeee888 eddeee888 Apr 8, 2025

Choose a reason for hiding this comment

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

Nice, that makes sense. It's done here: 95258f5#diff-861d37e0c7d8a1469880c96a03a643fdb722c21b7304a4324a42c85c59e7ef8dL138-L144

There were some options I also considered
e.g. throw new NoTypeDefinitionsFound('No type defintions found', { pointerList }). However, the message is just a duplicate.

So passing pointerList as the first param feels better, even though most Error's first param is a message

- Rename custom error to NoTypeDefinitionsFound to match the rest of implementation
- Let custom error take pointerList and encapsulate error message logic
- Update tests to handle sync vs async use cases
- Concat rows instead of using template literal strings to have better formatting
@@ -151,3 +145,17 @@ function prepareResult({
debugTimerEnd('@graphql-tools/load: prepareResult');
return sortedResult;
}

export class NoTypeDefinitionsFound extends Error {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Note: I've changed this from NoDocumentFoundError to NoTypeDefinitionsFound to better match other names in this file

Comment on lines 151 to 156
const rows: string[] = [];
rows.push('Unable to find any GraphQL type definitions for the following pointers:');
pointerList.forEach(pointer => {
rows.push(`- ${pointer}`);
});
const message = rows.join('\n');
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I'm joining strings this way because I find the template literal adds a lot of extra spacing on the left of the terminal.

@@ -93,14 +93,22 @@ describe('documentsFromGlob', () => {
});

test(`Should throw on empty files and empty result`, async () => {
expect.assertions(2);
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I've switched back to try/catch with an expect.assertions(2) and no expect in the happy path. This helps us fail the test if load somehow succeeds

@eddeee888 eddeee888 requested a review from ardatan April 8, 2025 13:07
@@ -135,13 +135,7 @@ function prepareResult({
const pointerList = Object.keys(pointerOptionMap);

if (pointerList.length > 0 && validSources.length === 0) {
throw new Error(`
Unable to find any GraphQL type definitions for the following pointers:
Copy link
Owner

Choose a reason for hiding this comment

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

It seems we lose the indentation here?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I've left a note about formatting here: #7093 (comment)
I think it could look better if it doesn't have the indentation & left-aligned. Otherwise, when it'd have some big spaces if an error happens in Codegen:

Screenshot 2025-04-09 at 11 52 38 pm

This is personal preference of course, I'll revert this to preserve the existing behaviour 🙂

@eddeee888 eddeee888 changed the title CODEGEN-334 - Throw custom NoDocumentFoundError if no document found whilst loading documents CODEGEN-334 - Throw custom NoTypeDefinitionsFound if no document found whilst loading documents Apr 9, 2025
@eddeee888 eddeee888 requested a review from ardatan April 9, 2025 14:00
@ardatan ardatan merged commit 4a33247 into ardatan:master Apr 9, 2025
20 checks passed
@eddeee888 eddeee888 deleted the throw-no-document-found-error-when-loading branch April 10, 2025 13:43
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