Join us from October 8-10 in New York City to learn the latest tips, trends, and news about GraphQL Federation and API platform engineering.Join us for GraphQL Summit 2024 in NYC
Docs
Start for Free

Schema Link

Assists with mocking and server-side rendering


Overview

The schema link provides a graphql execution environment, which allows you to perform on a provided schema. This type of behavior is commonly used for server-side rendering (SSR) to avoid network calls and mocking data. While the schema link could provide graphql results on the client, currently the graphql execution layer is too heavy weight for practical application.

To unify your state management with client-side GraphQL operations, refer to 's local state management functionality. It integrates with the Apollo Client cache and is much more lightweight.

Installation

npm install @apollo/client --save

Usage

Server Side Rendering

When performing SSR on the same server, you can use this library to avoid making network calls.

import { ApolloClient, InMemoryCache } from '@apollo/client';
import { SchemaLink } from '@apollo/client/link/schema';
import schema from './path/to/your/schema';
const graphqlClient = new ApolloClient({
cache: new InMemoryCache(),
ssrMode: true,
link: new SchemaLink({ schema })
});

Mocking

For more detailed information about mocking, refer to the graphql-tools documentation.

import { ApolloClient, InMemoryCache } from '@apollo/client';
import { SchemaLink } from '@apollo/client/link/schema';
import { makeExecutableSchema, addMockFunctionsToSchema } from 'graphql-tools';
const typeDefs = `
Query {
...
}
`;
const mocks = {
Query: () => ...,
Mutation: () => ...
};
const schema = makeExecutableSchema({ typeDefs });
const schemaWithMocks = addMockFunctionsToSchema({
schema,
mocks
});
const apolloCache = new InMemoryCache(window.__APOLLO_STATE__);
const graphqlClient = new ApolloClient({
cache: apolloCache,
link: new SchemaLink({ schema: schemaWithMocks })
});

Options

The SchemaLink constructor can be called with an object with the following properties:

OptionDescription
schemaAn executable graphql schema
rootValueThe root value that is passed to the resolvers (i.e. the first parameter for the rootQuery)
contextAn object passed to the resolvers, following the graphql specification or a function that accepts the operation and returns the resolver context. The resolver context may contain all the data-fetching connectors for an operation.
validateEnable validation of incoming queries against the local schema before execution, returning validation errors in result.errors, just like a non-local GraphQL endpoint typically would.
Previous
Retry
Next
Subscriptions (newer protocol)
Rate articleRateEdit on GitHubEditForumsDiscord

© 2024 Apollo Graph Inc., d/b/a Apollo GraphQL.

Privacy Policy

Company