Skip to content

Instantly share code, notes, and snippets.

@alexandrebodin
Last active November 12, 2017 01:12
Show Gist options
  • Save alexandrebodin/5f537ab7088d791dd4d218f7d954b0cf to your computer and use it in GitHub Desktop.
Save alexandrebodin/5f537ab7088d791dd4d218f7d954b0cf to your computer and use it in GitHub Desktop.
implementing a directive with custom resolver to handle globalIds easily
const {
GraphQLObjectType,
GraphQLScalarType,
TypeInfo,
visit,
visitWithTypeInfo,
findDeprecatedUsages,
parse,
validate,
execute,
graphql,
buildSchema,
buildASTSchema,
print,
} = require('graphql');
var source = `
type Query {
hello(id: GlobalID): Hello
}
type Hello {
id: GlobalID @globalId(prefix: "event")
name: String
}
scalar GlobalID
directive @globalId (name: String) on FIELD_DEFINITION
`;
const globalId = new GraphQLScalarType({
name: 'GlobalID',
serialize: value => {
return value;
},
parseValue: value => ast.value.split('|')[1],
parseLiteral: ast => ast.value.split('|')[1],
});
const schema = buildSchema(source);
const tmp = schema.getType('GlobalID');
Object.keys(globalId).forEach(key => {
tmp[key] = globalId[key];
})
const typeMap = schema.getTypeMap();
Object.keys(typeMap).forEach(typeKey => {
const type = typeMap[typeKey];
if (type instanceof GraphQLObjectType) {
const fields = type.getFields();
Object.keys(fields).forEach(fieldName => {
const field = fields[fieldName];
if (!field.astNode) return;
const directives = field.astNode.directives;
if (directives.some(directive => directive.name.value === 'globalId')) {
const globalDirective = directives.find(d => d.name.value === 'globalId');
const prefix = globalDirective.arguments.find(arg => arg.name.value === 'prefix');
field.resolve = ({ id }) => prefix.value.value + '|' + id;
}
});
}
});
// The root provides a resolver function for each API endpoint
var root = {
hello: ({ id }, ctx, info) => {
console.log(id);
return {
id: 1,
name: 1,
};
},
};
const query = `{ hello (id: "event|2") { id }}`;
graphql(schema, query, root).then(res => {
console.log(res);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment