GraphQL Ruby Client for JavaScript
The `graphql-ruby-client` is a JavaScript client library specifically designed to integrate with `graphql-ruby` servers. It facilitates frontend interactions by generating JavaScript modules from `.graphql` query, mutation, and subscription files, which are then consumed by popular client-side GraphQL libraries such as Apollo Client, Relay, or urql. Currently at version 1.14.9, the package demonstrates an active, incremental release cadence focused on bug fixes and feature enhancements, with the latest update being a couple of months ago. Its key differentiator lies in its tight integration with `graphql-ruby`, offering specialized runtime utilities like fetchers for various subscription backends (e.g., Ably, Pusher) and tooling for persisted queries, which are optimized for the Ruby GraphQL ecosystem. This makes it a primary choice for JavaScript frontends interfacing with Ruby-based GraphQL APIs, particularly within Rails applications.
Common errors
-
Module not found: Error: Can't resolve 'graphql-ruby-client'
cause The package `graphql-ruby-client` is not installed or incorrectly referenced in your project's dependencies.fixRun `npm install graphql-ruby-client` or `yarn add graphql-ruby-client` to install the package. Verify the import path is correct. -
TypeError: createFetcher is not a function
cause Attempting to use `createFetcher` (or similar utilities) with an incorrect import statement, often `require()` in an ESM context or a wrong named/default import.fixEnsure you are using `import { createFetcher } from 'graphql-ruby-client';` for named exports, or `import createAblyFetcher from 'graphql-ruby-client/subscriptions/createAblyFetcher';` for default exports from subpaths, and that your environment supports ESM. -
Invariant Violation: Could not find 'client' in the context or pass it as a prop
cause This Apollo Client error indicates that the `ApolloProvider` is missing or improperly configured, preventing components from accessing the Apollo Client instance.fixEnsure your root React component (or equivalent in other frameworks) is wrapped with `<ApolloProvider client={yourApolloClientInstance}>` and that `yourApolloClientInstance` is correctly initialized with the `graphql-ruby-client` fetcher.
Warnings
- gotcha The `graphql-ruby-client` package is licensed under LGPLv3. For commercial use cases, particularly without open-sourcing derivative works, a special commercial license is required, typically obtained by becoming a `graphql-pro` customer. Failing to adhere to the LGPLv3 terms can have significant legal implications for proprietary applications.
- breaking Version 1.11.6 introduced a breaking change related to `FieldExtension` where `after_resolve` callbacks now receive extended values instead of original values. While primarily a server-side change, it can affect client-side expectations or generated code if your GraphQL Ruby server utilizes custom field extensions and your client logic depends on the exact data passed through these extensions.
- gotcha This library is designed for the `graphql-ruby` server. While it integrates with generic JavaScript GraphQL clients like Apollo, its primary benefits (e.g., specific fetchers, persisted query tooling) are realized when paired with a `graphql-ruby` backend. Using it with other GraphQL server implementations might lead to less optimal performance or require custom configuration.
- gotcha The `graphql-ruby-client` package primarily provides a code generator and runtime utilities that consume *generated* JavaScript modules from `.graphql` files. Direct ad-hoc query execution without prior generation is not its main intended workflow, and developers should familiarize themselves with the generation process.
Install
-
npm install graphql-ruby-client -
yarn add graphql-ruby-client -
pnpm add graphql-ruby-client
Imports
- createFetcher
const createFetcher = require('graphql-ruby-client').createFetcher;import { createFetcher } from 'graphql-ruby-client'; - Operation
import Operation from 'graphql-ruby-client/Operation';
import { Operation } from 'graphql-ruby-client'; - createAblyFetcher
import { createAblyFetcher } from 'graphql-ruby-client';import createAblyFetcher from 'graphql-ruby-client/subscriptions/createAblyFetcher';
Quickstart
import { ApolloClient, InMemoryCache, ApolloProvider, HttpLink } from '@apollo/client';
import { createFetcher } from 'graphql-ruby-client';
// Assuming 'QueryName' and 'QueryName_variables' are generated from your .graphql files
// In a real application, these would be imported from your generated code.
const GENERATED_QUERY = {
id: 'some-unique-query-id',
document: `query SomeQuery($id: ID!) {
user(id: $id) {
id
name
email
}
}`,
ast: { /* full GraphQL AST would be here */ },
variables: (id) => ({ id }),
operationName: 'SomeQuery'
};
// Configure the HTTP endpoint for your GraphQL Ruby server
const httpLink = new HttpLink({ uri: 'http://localhost:3000/graphql' });
// Create a fetcher compatible with Apollo Link, using graphql-ruby-client's utility
// This will handle the specific serialization/deserialization for graphql-ruby
const clientFetcher = createFetcher({
link: httpLink,
// In a production setup, you'd likely pass a more robust link chain
});
const client = new ApolloClient({
link: clientFetcher,
cache: new InMemoryCache(),
});
// Example of executing a generated query
async function fetchUser(userId: string) {
try {
const { data } = await client.query({
query: GENERATED_QUERY.document,
variables: GENERATED_QUERY.variables(userId),
operationName: GENERATED_QUERY.operationName,
});
console.log('Fetched User:', data.user);
return data.user;
} catch (error) {
console.error('Error fetching user:', error);
throw error;
}
}
// Example usage:
fetchUser('123').then(user => {
if (user) {
console.log(`User name: ${user.name}`);
}
});