Created
September 19, 2017 14:32
-
-
Save apostopher/018220f32d6742fbfd602b83357ff5ae to your computer and use it in GitHub Desktop.
Relay global id input type
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 { 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