graphql_controller.rb 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # Copyright (C) 2012-2021 Zammad Foundation, http://zammad-foundation.org/
  2. class GraphqlController < ApplicationController
  3. # If accessing from outside this domain, nullify the session
  4. # This allows for outside API access while preventing CSRF attacks,
  5. # but you'll have to authenticate your user separately
  6. # protect_from_forgery with: :null_session
  7. # Handled in the GraphQL processing, not on controller level.
  8. skip_before_action :verify_csrf_token
  9. prepend_before_action :authentication_check_only
  10. def execute
  11. variables = prepare_variables(params[:variables])
  12. query = params[:query]
  13. operation_name = params[:operationName]
  14. context = {
  15. current_user: current_user,
  16. controller: self,
  17. }
  18. result = Gql::ZammadSchema.execute(query, variables: variables, context: context, operation_name: operation_name)
  19. render json: result
  20. rescue => e
  21. raise e if !Rails.env.development?
  22. handle_error_in_development(e)
  23. end
  24. private
  25. # Handle variables in form data, JSON body, or a blank value
  26. def prepare_variables(variables_param)
  27. case variables_param
  28. when String
  29. if variables_param.present?
  30. JSON.parse(variables_param) || {}
  31. else
  32. {}
  33. end
  34. when Hash
  35. variables_param
  36. when ActionController::Parameters
  37. variables_param.to_unsafe_hash # GraphQL-Ruby will validate name and type of incoming variables.
  38. when nil
  39. {}
  40. else
  41. raise ArgumentError, "Unexpected parameter: #{variables_param}"
  42. end
  43. end
  44. def handle_error_in_development(e)
  45. logger.error e.message
  46. logger.error e.backtrace.join("\n")
  47. render json: { errors: [{ message: e.message, backtrace: e.backtrace }], data: {} }, status: :internal_server_error
  48. end
  49. end