Skip to content

Instantly share code, notes, and snippets.

@elliottsj
Last active January 28, 2021 04:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elliottsj/fa7042c0588ea6df1bc2f02f583d1100 to your computer and use it in GitHub Desktop.
Save elliottsj/fa7042c0588ea6df1bc2f02f583d1100 to your computer and use it in GitHub Desktop.
An example of using Apollo graphql-tools `mergeSchemas` to delegate to a non-root sub-field
import { GraphQLSchema, Kind } from 'graphql';
import {
makeExecutableSchema,
mergeSchemas,
transformSchema,
RenameRootFields,
RenameTypes,
WrapQuery,
} from 'graphql-tools';
const issueSchema = makeExecutableSchema({
typeDefs: `
type Issue {
id: ID!
authorUsername: String!
}
type Viewer {
issue(id: ID!): Issue
}
type Query {
viewer(token: String!): Viewer
}
`
});
const userSchema = makeExecutableSchema({
typeDefs: `
type User {
id: ID!
username: String
}
type Viewer {
user(username: String!): User
}
type Query {
viewer(token: String!): Viewer
}
`
});
const transformedUserSchema = transformSchema(userSchema, [
new RenameTypes((name: string) => `UserSchema_${name}`),
new RenameRootFields(
(_operation: 'Query' | 'Mutation' | 'Subscription', name: string) => `UserSchema_${name}`,
),
]);
const linkTypeDefs = `
extend type Issue {
author: User
}
`;
mergeSchemas({
schemas: [issueSchema, transformedUserSchema, linkTypeDefs],
resolvers: {
Issue: {
author: {
fragment: `... on Issue { authorUsername }`,
resolve(issue, _args, context, info) {
return info.mergeInfo.delegateToSchema({
schema: userSchema,
operation: 'query',
fieldName: 'viewer',
args: {
token: info.variableValues.token,
},
context,
info,
transforms: [
/**
* Use WrapQuery to delegate to a sub-field of userSchema, approximately equivalent to:
*
* query {
* viewer(token: $token) {
* user(username: $username) {
* ...subtree
* }
* }
* }
*/
new WrapQuery(
['viewer'],
subtree => ({
kind: Kind.SELECTION_SET,
selections: [
{
kind: Kind.FIELD,
name: {
kind: Kind.NAME,
value: 'user',
},
arguments: [
{
kind: Kind.ARGUMENT,
name: { kind: Kind.NAME, value: 'username' },
value: { kind: Kind.STRING, value: issue.authorUsername },
},
],
selectionSet: subtree,
},
],
}),
result => result && result.user,
),
...transformedUserSchema.transforms,
],
});
},
},
},
},
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment