Schema Link

Assists with mocking and server-side rendering


Overview

The schema link provides a graphql execution environment , which allows you to perform GraphQL operations 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 Apollo Client'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.

JavaScript
1import { ApolloClient, InMemoryCache } from '@apollo/client';
2import { SchemaLink } from '@apollo/client/link/schema';
3
4import schema from './path/to/your/schema';
5
6const graphqlClient = new ApolloClient({
7  cache: new InMemoryCache(),
8  ssrMode: true,
9  link: new SchemaLink({ schema })
10});

Mocking

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

JavaScript
1import { ApolloClient, InMemoryCache } from '@apollo/client';
2import { SchemaLink } from '@apollo/client/link/schema';
3import { makeExecutableSchema, addMockFunctionsToSchema } from 'graphql-tools';
4
5const typeDefs = `
6  Query {
7  ...
8  }
9`;
10
11const mocks = {
12  Query: () => ...,
13  Mutation: () => ...
14};
15
16const schema = makeExecutableSchema({ typeDefs });
17const schemaWithMocks = addMockFunctionsToSchema({
18  schema,
19  mocks
20});
21
22const apolloCache = new InMemoryCache(window.__APOLLO_STATE__);
23
24const graphqlClient = new ApolloClient({
25  cache: apolloCache,
26  link: new SchemaLink({ schema: schemaWithMocks })
27});

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.