graphql_controller.rb 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # frozen_string_literal: true
  2. class API::GraphqlController < API::ApplicationController
  3. include UserAuthentication
  4. def execute
  5. render json: PokemonTradeSchema.execute(
  6. params[:query],
  7. execute_params(params),
  8. )
  9. rescue StandardError => e
  10. raise e unless Rails.env.development?
  11. handle_error_in_development(e)
  12. end
  13. private
  14. def execute_params(hash)
  15. {
  16. operation_name: hash[:operationName],
  17. variables: ensure_hash(hash[:variables]),
  18. context: {controller: self, current_user: current_user},
  19. }
  20. end
  21. # Handle form data, JSON body, or a blank value
  22. def ensure_hash(ambiguous_param)
  23. case ambiguous_param
  24. when String
  25. if ambiguous_param.present?
  26. ensure_hash(JSON.parse(ambiguous_param))
  27. else
  28. {}
  29. end
  30. when Hash, ActionController::Parameters
  31. ambiguous_param
  32. when nil
  33. {}
  34. else
  35. raise ArgumentError, "Unexpected parameter: #{ambiguous_param}"
  36. end
  37. end
  38. def handle_error_in_development(err)
  39. logger.error err.message
  40. logger.error err.backtrace.join("\n")
  41. render json: {
  42. errors: [{message: err.message, backtrace: err.backtrace}],
  43. data: {},
  44. }, status: :internal_server_error
  45. end
  46. end