Last active
January 28, 2021 04:29
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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