Created
June 2, 2016 13:32
-
-
Save rmosolgo/25e81d5bd275867c86ab1445036ad3ef to your computer and use it in GitHub Desktop.
Return an error message in a GraphQL field with graphql-ruby
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
# This object returns the _new_ state and any error message during the transition. | |
# So in the response, you could check for the presence of an error message. | |
# (In the case of an error, presumably the state would not change.) | |
StateMachineTransitionType = GraphQL::ObjectType.define do | |
name "StateMachineTransition" | |
field :error_message, types.String | |
field :state, types.String # Could also define StateMachineStateEnum | |
end | |
MutationType = GraphQL::ObjectType.define do | |
name "Mutation" | |
# Attempt to move states. | |
# Rescue from a failed transition and grab the error. | |
# Return _both_ the new state (which may be unchanged) and the error message (which may be nil) | |
field :transition_state_machine, StateMachineTransitionType do | |
argument :to_state, !types.String # Could also define StateMachineStateEnum | |
resolve -> (obj, args, ctx) { | |
obj # => StateMachine | |
error_message = nil | |
begin | |
obj.transition_to(args[:to_state]) | |
rescue StateMachine::TransitionFailedError => err | |
error_message = err.message | |
end | |
# IRL define a class like StateMachineTransitionResponse instead of OpenStruct | |
OpenStruct.new( | |
state: obj.state, | |
error_message: error_message, | |
) | |
} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment