The ultimate guide to Schema Stitching in GraphQL
Overriding existing queries and mutations
While tailoring a new schema from existing GraphQL schemas using schema stitching, we can also override the existing queries and mutations. This is particularly useful when:
- Adding custom validation to the resolvers
- Data clean-up and case transformation
Adding custom checks
Let us consider a gaming room GraphQL API that serves the following schema.
# roottype Query { game: game}
type game { id: Int, name: String, type: String, multiplayer: Boolean, ip: String}
We will now add a custom validation to the game
query such that this query passes through only after 17:00 (so that kids don’t game during the day ;-)).
- Create a remote executable schema from the the existing
game
API.
2. Write a custom resolver to add custom validation to the game
query.
3. Merge the executable game
schema with our custom resolvers:
4. Serve the new schema:
Data cleanup
We might want to sanitize or modify some data in our GraphQL server before we delegate it to some underlying GraphQL API. This can be achieved with the help of a custom resolver as illustrated below.
Let us consider a simple user
profile schema where the insert_user
mutation has to be delegated to an underlying schema. Before delegating, the email in the data has to be converted to lowercase.
The algorithm is as follows:
- Create a remote executable schema with the
makeRemoteExecutableSchema()
function:
2. Create a custom resolver for converting the email to lowercase.
3. Merge the executable schema with the resolver using the mergeSchemas
function:
4. Serve the merged schema with a new instance of the apollo-server: