Created
September 7, 2017 13:59
-
-
Save wmertens/6606838bc59681cf2bb39bb23a8d9568 to your computer and use it in GitHub Desktop.
Add dataloaders to graphql context
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 DataLoader from 'dataloader' | |
import {graphqlExpress} from 'graphql-server-express' | |
import schema from './schema' | |
import db from './database' | |
const contextFromReq = req => { | |
const {session} = req | |
const loaders = {} | |
const getLoader = (id, makeGetter) => { | |
const loader = loaders[id] | |
if (loader) return loader | |
const l = new DataLoader(makeGetter(db)) | |
loaders[id] = l | |
return l | |
} | |
return { | |
db, | |
session, | |
getLoader, | |
} | |
} | |
export default graphqlExpress(req => { | |
const context = contextFromReq(req) | |
// http://dev.apollodata.com/tools/graphql-server/setup.html#graphqlOptions | |
return {context, schema} | |
}) |
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
const makeIdGetter = db => ids => db.fooTable.getAll(ids) | |
const query = { | |
foo: { | |
type: Foo, | |
args: { | |
id: {type: GraphQLID}, | |
}, | |
resolve: (root, {id}, {getLoader}) => getLoader('houseId', makeIdGetter).load(id), | |
}, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment