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

enhance(transport-rest): use the default fetch if no fetch exists in the transport context #8351

Merged
merged 1 commit into from
Jan 31, 2025

Conversation

ardatan
Copy link
Owner

@ardatan ardatan commented Jan 31, 2025

Fixes graphql-hive/gateway#1

Summary by CodeRabbit

  • Bug Fixes
    • Improved fetch function handling in the GraphQL Mesh REST transport to ensure compatibility across different environments
    • Added fallback mechanism for fetch implementation when no context or global fetch is available

Copy link
Contributor

coderabbitai bot commented Jan 31, 2025

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/transports/rest/src/directives/httpOperation.ts

Oops! Something went wrong! :(

ESLint: 9.19.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.

📝 Walkthrough

Walkthrough

The pull request introduces a patch for the @graphql-mesh/transport-rest package to improve fetch function handling. The primary change involves modifying the import and usage of the fetch function in the httpOperation.ts file. The modification ensures that when no fetch implementation is provided in the context or globally, a default fetch from @whatwg-node/fetch is used, preventing potential runtime errors and enhancing the package's compatibility across different environments.

Changes

File Change Summary
.changeset/seven-crabs-cough.md Patch declaration for @graphql-mesh/transport-rest package
packages/transports/rest/src/directives/httpOperation.ts Modified fetch import to include fallback to defaultFetch

Assessment against linked issues

Objective Addressed Explanation
Resolve fetch function not found error [#1]
Provide fallback fetch mechanism

Poem

🐰 In the realm of GraphQL's dance,
A fetch function finds its chance,
With whatwg's magic touch so neat,
No error shall make our code retreat!
Mesh flows smooth, no fetch despair,
A rabbit's fix beyond compare! 🌈


📜 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 93b17fe and 9768df0.

📒 Files selected for processing (2)
  • .changeset/seven-crabs-cough.md (1 hunks)
  • packages/transports/rest/src/directives/httpOperation.ts (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (14)
  • GitHub Check: e2e / node v22
  • GitHub Check: e2e / node v20
  • GitHub Check: e2e / node v18
  • GitHub Check: check
  • GitHub Check: integration / node 22
  • GitHub Check: integration / node 20
  • GitHub Check: integration / node 18
  • GitHub Check: release / snapshot
  • GitHub Check: unit / node 22
  • GitHub Check: unit / node 20
  • GitHub Check: unit / node 18
  • GitHub Check: apollo-federation-compatibility
  • GitHub Check: deployment
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (3)
.changeset/seven-crabs-cough.md (1)

1-5: LGTM!

The changeset correctly describes the patch version bump and the enhancement to use @whatwg-node/fetch as a fallback.

packages/transports/rest/src/directives/httpOperation.ts (2)

12-12: LGTM!

The import statement correctly imports the default fetch function from @whatwg-node/fetch along with other necessary utilities.


299-299: LGTM! The fetch function fallback chain is well-implemented.

The implementation follows a clear priority order:

  1. Use context.fetch if available
  2. Fallback to globalFetch if provided
  3. Finally, use defaultFetch from @whatwg-node/fetch

This ensures backward compatibility while providing a reliable default implementation.

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 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. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @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.

@ardatan
Copy link
Owner Author

ardatan commented Jan 31, 2025

@coderabbitai generate unit testing code for this file.

Copy link
Contributor

coderabbitai bot commented Jan 31, 2025

Tip

For best results, initiate chat on the files or code changes.

@ardatan Here are the unit tests for the REST transport implementation:

import { describe, it, expect, vi } from 'vitest';
import RESTTransport from '../src/index';
import { processDirectives } from '../src/directives/process';
import { createDefaultExecutor } from '@graphql-mesh/transport-common';

// Mock dependencies
vi.mock('@graphql-mesh/transport-common', () => ({
  createDefaultExecutor: vi.fn(),
}));

vi.mock('../src/directives/process', () => ({
  processDirectives: vi.fn(),
}));

describe('REST Transport', () => {
  const mockFetch = vi.fn();
  const mockPubsub = { publish: vi.fn(), subscribe: vi.fn() };
  const mockLogger = { info: vi.fn(), error: vi.fn() };
  const mockSubgraph = { schema: {} };
  
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('should initialize executor with correct parameters', () => {
    const transportEntry = {
      options: {
        timeout: 5000,
        queryParams: { version: '1.0' },
      },
    };

    RESTTransport.getSubgraphExecutor({
      transportEntry,
      subgraph: mockSubgraph,
      fetch: mockFetch,
      pubsub: mockPubsub,
      logger: mockLogger,
    });

    // Verify processDirectives was called with correct args
    expect(processDirectives).toHaveBeenCalledWith(mockSubgraph, {
      globalFetch: mockFetch,
      pubsub: mockPubsub,
      logger: mockLogger,
      timeout: 5000,
      queryParams: { version: '1.0' },
    });
  });

  it('should create and return default executor with processed schema', () => {
    const mockProcessedSchema = { processed: true };
    (processDirectives as jest.Mock).mockReturnValue(mockProcessedSchema);
    
    const mockExecutor = vi.fn();
    (createDefaultExecutor as jest.Mock).mockReturnValue(mockExecutor);

    const result = RESTTransport.getSubgraphExecutor({
      transportEntry: { options: {} },
      subgraph: mockSubgraph,
      fetch: mockFetch,
      pubsub: mockPubsub,
      logger: mockLogger,
    });

    expect(createDefaultExecutor).toHaveBeenCalledWith(mockProcessedSchema);
    expect(result).toBe(mockExecutor);
  });

  it('should work without optional transport options', () => {
    RESTTransport.getSubgraphExecutor({
      transportEntry: { options: {} },
      subgraph: mockSubgraph,
      fetch: mockFetch,
      pubsub: mockPubsub,
      logger: mockLogger,
    });

    expect(processDirectives).toHaveBeenCalledWith(mockSubgraph, {
      globalFetch: mockFetch,
      pubsub: mockPubsub,
      logger: mockLogger,
    });
  });

  it('should pass fetch function to process directives', () => {
    const customFetch = vi.fn();
    
    RESTTransport.getSubgraphExecutor({
      transportEntry: { options: {} },
      subgraph: mockSubgraph,
      fetch: customFetch,
      pubsub: mockPubsub,
      logger: mockLogger,
    });

    expect(processDirectives).toHaveBeenCalledWith(
      expect.anything(),
      expect.objectContaining({
        globalFetch: customFetch,
      }),
    );
  });
});

This test suite covers:

  1. Proper initialization of the executor with all parameters
  2. Correct passing of transport options to processDirectives
  3. Integration with the default executor
  4. Handling of the fetch function
  5. Cases with and without optional transport options

The tests use Vitest as the testing framework and include mocks for all external dependencies. You'll need to place this file in the packages/transports/rest/tests directory with a name like index.test.ts.

Make sure to add the following dev dependencies to your package:

{
  "devDependencies": {
    "vitest": "latest",
    "@types/jest": "latest"
  }
}
🔗 Analysis chain

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Find relevant files
fd -t f -e ts "transport-rest" 

Length of output: 30


Script:

#!/bin/bash
# Read the contents of the files
for file in $(fd -t f -e ts "transport-rest"); do
  echo "=== $file ==="
  cat "$file"
  echo
done

Length of output: 31


Script:

#!/bin/bash
# Search for files containing relevant keywords
rg -l "transport.*fetch|fetch.*transport" --type ts

Length of output: 129


Script:

#!/bin/bash
# Read the REST transport file
cat "packages/transports/rest/src/index.ts"

Length of output: 971

Copy link
Contributor

Apollo Federation Subgraph Compatibility Results

Federation 1 Support Federation 2 Support
_service🟢
@key (single)🟢
@key (multi)🟢
@key (composite)🟢
repeatable @key🟢
@requires🟢
@provides🟢
federated tracing🟢
@link🟢
@shareable🟢
@tag🟢
@override🟢
@inaccessible🟢
@composeDirective🟢
@interfaceObject🟢

Learn more:

Copy link
Contributor

🚀 Snapshot Release (alpha)

The latest changes of this PR are available as alpha on npm (based on the declared changesets):

Package Version Info
@graphql-mesh/json-schema 0.108.15-alpha-20250131092314-9768df0daaefb5600beeda0845e991d3513b3af8 npm ↗︎ unpkg ↗︎
@graphql-mesh/openapi 0.108.16-alpha-20250131092314-9768df0daaefb5600beeda0845e991d3513b3af8 npm ↗︎ unpkg ↗︎
@graphql-mesh/raml 0.108.14-alpha-20250131092314-9768df0daaefb5600beeda0845e991d3513b3af8 npm ↗︎ unpkg ↗︎
@omnigraph/json-schema 0.108.14-alpha-20250131092314-9768df0daaefb5600beeda0845e991d3513b3af8 npm ↗︎ unpkg ↗︎
@omnigraph/openapi 0.108.16-alpha-20250131092314-9768df0daaefb5600beeda0845e991d3513b3af8 npm ↗︎ unpkg ↗︎
@omnigraph/raml 0.108.14-alpha-20250131092314-9768df0daaefb5600beeda0845e991d3513b3af8 npm ↗︎ unpkg ↗︎
@graphql-mesh/transport-rest 0.8.14-alpha-20250131092314-9768df0daaefb5600beeda0845e991d3513b3af8 npm ↗︎ unpkg ↗︎

Copy link
Contributor

💻 Website Preview

The latest changes are available as preview in: https://a0bff8b3.graphql-mesh.pages.dev

@ardatan ardatan merged commit 0b6ee9c into master Jan 31, 2025
19 checks passed
@ardatan ardatan deleted the default-fetch-rest branch January 31, 2025 09:27
@coderabbitai coderabbitai bot mentioned this pull request Feb 20, 2025
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.

GraphQL Mesh with OpenAPI cannot find fetch even if it is defined using getExecutorForUnifiedGraph
1 participant