Skip to content

Instantly share code, notes, and snippets.

@apostopher
Created September 19, 2017 14:32
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 apostopher/018220f32d6742fbfd602b83357ff5ae to your computer and use it in GitHub Desktop.
Save apostopher/018220f32d6742fbfd602b83357ff5ae to your computer and use it in GitHub Desktop.
Relay global id input type
import { GraphQLNonNull } from 'graphql';
import { fromGlobalId } from 'graphql-relay';
export const RelayGlobalID = new GraphQLScalarType({
name: 'RelayGlobalID',
description: 'The RelayGlobalID scalar type represents a globalIdField in relay.',
serialize(value) {
return value;
},
parseValue(value) {
// parse the local id from global id
try {
return fromGlobalId(value).id;
} catch (error) {
throw new GraphQLError('Invalid global id format.');
}
},
parseLiteral(ast) {
// parse the local id from global id
try {
return fromGlobalId(ast.value).id;
} catch (error) {
throw new GraphQLError('Invalid global id format.');
}
}
});
// Example usage
const deleteCommentMutation = {
type: CommentType,
description: 'Delete a comment with id and return the comment that was deleted.',
args: {
id: {
type: new GraphQLNonNull(RelayGlobalID),
description: 'The globalId of the comment.',
}
},
resolve: (value, { id }) => {
// `id` here will be the real id. not the global id
return CommentService.delete(id);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment