Skip to content

Instantly share code, notes, and snippets.

@giautm
Created February 3, 2017 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save giautm/bcfee5c173cb3b256ae9cd4aaa62f11b to your computer and use it in GitHub Desktop.
Save giautm/bcfee5c173cb3b256ae9cd4aaa62f11b to your computer and use it in GitHub Desktop.
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