Created
February 3, 2017 18:19
-
-
Save giautm/bcfee5c173cb3b256ae9cd4aaa62f11b 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 { | |
GraphQLObjectType, | |
} = require('graphql'); | |
const { | |
fromGlobalId, | |
nodeDefinitions, | |
} = require('graphql-relay'); | |
const modelsRegistry = {}; | |
const { nodeInterface, nodeField } = nodeDefinitions( | |
findObjectByGlobalId, objectToGraphQLType); | |
function findObjectByGlobalId(globalId, { loaders }) { | |
const { type, id } = fromGlobalId(globalId); | |
return loaders.get(type).load(id); | |
} | |
function objectToGraphQLType(obj) { | |
if (obj && obj.constructor) { | |
const { modelName } = obj.constructor; | |
return modelsRegistry[modelName] || null; | |
} | |
return null; | |
} | |
const registerModel = (graphQLObjectTypeConfig) => { | |
const { name, interfaces } = graphQLObjectTypeConfig; | |
if (modelsRegistry[name] === undefined) { | |
modelsRegistry[name] = new GraphQLObjectType(Object.assign({}, | |
graphQLObjectTypeConfig, { | |
interfaces: [nodeInterface].concat(interfaces || []), | |
})); | |
} | |
return modelsRegistry[name]; | |
}; | |
module.exports = { | |
nodeField, | |
nodeInterface, | |
registerModel, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment