Last active
January 8, 2018 16:23
-
-
Save Piefayth/3a5d101ff34fdb822d7e3963e00edb03 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const express = require('express') | |
const graphqlHTTP = require('express-graphql') | |
const { makeExecutableSchema, mergeSchemas } = require('graphql-tools') | |
const _ = require('lodash') | |
const app = express(); | |
const standaloneResolvers = { | |
Query: { | |
standalone: (data) => { | |
return { foo: "foo" } | |
} | |
}, | |
Standalone: { | |
foo: (data) => { | |
return "Standalone.foo should always return this string" | |
} | |
} | |
} | |
const dependantResolvers = { | |
Query: { | |
dependant: () => { | |
return { | |
dontNeedExternalTypeField: "baz" | |
} | |
} | |
} | |
} | |
const StandaloneSchema = makeExecutableSchema({ | |
typeDefs: ` | |
type Query { | |
standalone: Standalone | |
} | |
type Standalone { | |
foo: String | |
} | |
`, | |
resolvers: standaloneResolvers | |
}) | |
const DependantSchema = makeExecutableSchema({ | |
typeDefs: ` | |
type Query { | |
dependant: Dependant | |
} | |
type Dependant { | |
dontNeedExternalTypeField: String | |
} | |
`, | |
resolvers: dependantResolvers | |
}) | |
const linkTypeDefs = ` | |
extend type Dependant { | |
needExternalTypeField: Standalone | |
} | |
` | |
const linkResolvers = { | |
Dependant: { | |
needExternalTypeField: () => { | |
return ({ foo: "faz" }) | |
} | |
} | |
} | |
const mergedResolvers = mergeInfo => { | |
const merged = _.merge(standaloneResolvers, dependantResolvers, linkResolvers) | |
return merged | |
} | |
const mergedSchema = mergeSchemas({ | |
schemas: [StandaloneSchema, DependantSchema, linkTypeDefs], | |
resolvers: linkResolvers // passing "link resolvers" here will cause needExternalTypeField(Standalone).foo to always resolve to "faz", because the Standalone resolver never runs | |
}) // passing "mergedResolvers" (which include all top-level types) will correctly resolve needExternalTypeField(Standalone).foo to | |
// "Standalone.foo should always return this string" | |
/* Test Query | |
{ | |
standalone { | |
foo # Standalone.foo resolver always gets invoked | |
} | |
dependant { | |
needExternalTypeField { | |
foo # This is ALSO a Standalone.foo, but that resolver only gets invoked if | |
} # we include the top-level type resolvers in the linkResolvers via mergedResolvers | |
} | |
} | |
*/ | |
app.use('/graphql', graphqlHTTP({ | |
schema: mergedSchema, | |
graphiql: true | |
})) | |
app.listen(4000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment