zammad_schema.rb 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class Gql::ZammadSchema < GraphQL::Schema
  3. mutation Gql::EntryPoints::Mutations
  4. query Gql::EntryPoints::Queries
  5. subscription Gql::EntryPoints::Subscriptions
  6. context_class Gql::Context::CurrentUserAware
  7. use GraphQL::Subscriptions::ActionCableSubscriptions, broadcast: true, default_broadcastable: false
  8. # Enable batch loading
  9. use GraphQL::Batch
  10. description 'This is the Zammad GraphQL API'
  11. # Set default limits to protect the system. Values may need to be adjusted in future.
  12. default_max_page_size 2000
  13. default_page_size 100
  14. max_complexity 10_000
  15. # Depth of 15 is needed for commmon introspection queries like Insomnia.
  16. max_depth 15
  17. TYPE_MAP = {
  18. ::Store => ::Gql::Types::StoredFileType,
  19. ::Taskbar => ::Gql::Types::User::TaskbarItemType,
  20. }.freeze
  21. ABSTRACT_TYPE_MAP = {
  22. ::Gql::Types::User::TaskbarItemEntityType => ::Gql::Types::User::TaskbarItemEntity::TicketCreateType,
  23. }.freeze
  24. # Union and Interface Resolution
  25. def self.resolve_type(abstract_type, obj, _ctx)
  26. TYPE_MAP[obj.class] || "Gql::Types::#{obj.class.name}Type".constantize
  27. rescue NameError
  28. ABSTRACT_TYPE_MAP[abstract_type]
  29. rescue
  30. raise GraphQL::RequiredImplementationMissingError, "Cannot resolve type for '#{obj.class.name}'."
  31. end
  32. # Relay-style Object Identification:
  33. # Return a string GUID for the internal ID.
  34. def self.id_from_internal_id(klass, internal_id)
  35. GlobalID.new(::URI::GID.build(app: GlobalID.app, model_name: klass.to_s, model_id: internal_id)).to_s
  36. end
  37. # Return a string GUID for `object`
  38. def self.id_from_object(object, _type_definition = nil, _query_ctx = nil)
  39. object.to_global_id.to_s
  40. end
  41. # Given a string GUID, find the object.
  42. def self.object_from_id(id, _query_ctx = nil, type: ActiveRecord::Base)
  43. GlobalID.find(id, only: type)
  44. end
  45. # Find the object, but also ensure its type and that it was actually found.
  46. def self.verified_object_from_id(id, type:)
  47. object_from_id(id, type: type) || raise(ActiveRecord::RecordNotFound, "Could not find #{type} #{id}")
  48. end
  49. # Like .verified_object_from_id, but with additional Pundit autorization.
  50. # This is only needed for objects where no validation takes place through their GraphQL type.
  51. def self.authorized_object_from_id(id, type:, user:, query: :show?)
  52. verified_object_from_id(id, type: type).tap do |object|
  53. Pundit.authorize user, object, query
  54. rescue Pundit::NotAuthorizedError => e
  55. # Map Pundit errors since we are not in a GraphQL built-in authorization context here.
  56. raise Exceptions::Forbidden, e.message
  57. end
  58. end
  59. # Given a string GUID, extract the internal ID.
  60. # This is very helpful if GUIDs have to be converted en-masse and then authorized in bulk using a scope.
  61. # Meanwhile using .object_from_id family would load (and, optionally, authorize) objects one by one.
  62. # Beware there's no built-in way to authorize given IDs in this method!
  63. #
  64. # @param id [String] GUID
  65. # @param type [Class] optionally filter to specific class only
  66. #
  67. # @return [Integer, nil]
  68. def self.internal_id_from_id(id, type: ActiveRecord::Base)
  69. internal_ids_from_ids([id], type:).first
  70. end
  71. # Given an array of string GUIDs, extract the internal IDs
  72. # @see .internal_id_from_id
  73. #
  74. # @param ids [Array<String>] GUIDs
  75. # @param type [Class] optionally filter to specific class only
  76. #
  77. # @return [Array<Integer>]
  78. def self.internal_ids_from_ids(...)
  79. local_uris_from_ids(...).map { |uri| uri.model_id.to_i }
  80. end
  81. # Given an array of string GUIDs, return GUID instances
  82. #
  83. # @param ids [Array<String>] GUIDs
  84. # @param type [Class] optionally filter to specific class only
  85. #
  86. # @return [Array<GlobalID>]
  87. def self.local_uris_from_ids(ids, type: ActiveRecord::Base)
  88. ids
  89. .map { |id| GlobalID.parse id }
  90. .select { |uri| (klass = uri.model_name.safe_constantize) && klass <= type }
  91. end
  92. def self.unauthorized_object(error)
  93. raise Exceptions::Forbidden, error.message # Add a top-level error to the response instead of returning nil.
  94. end
  95. def self.unauthorized_field(error)
  96. raise Exceptions::Forbidden, error.message # Add a top-level error to the response instead of returning nil.
  97. end
  98. RETHROWABLE_ERRORS = [GraphQL::ExecutionError, ArgumentError, IndexError, NameError, NoMethodError, RangeError, RegexpError, SystemCallError, ThreadError, TypeError, ZeroDivisionError].freeze
  99. # Post-process errors and enrich them with meta information for processing on the client side.
  100. rescue_from(StandardError) do |err, _obj, _args, ctx, field|
  101. if field&.path&.start_with?('Mutations.')
  102. user_locale = ctx.current_user?&.locale
  103. case err
  104. when ActiveRecord::RecordInvalid
  105. next { errors: build_record_invalid_errors(err.record, user_locale) }
  106. when ActiveRecord::RecordNotUnique
  107. next { errors: [ message: Translation.translate(user_locale, 'This object already exists.') ] }
  108. end
  109. end
  110. # Re-throw built-in errors that point to programming errors rather than problems with input or data - causes GraphQL processing to be aborted.
  111. RETHROWABLE_ERRORS.each do |klass|
  112. raise err if err.instance_of?(klass)
  113. end
  114. extensions = {
  115. type: err.class.name,
  116. }
  117. if Rails.env.local?
  118. extensions[:backtrace] = Rails.backtrace_cleaner.clean(err.backtrace)
  119. end
  120. # We need to throw an ExecutionError, all others would cause the GraphQL processing to die.
  121. raise GraphQL::ExecutionError.new(err.message, extensions: extensions)
  122. end
  123. def self.build_record_invalid_errors(record, user_locale)
  124. record.errors.map do |e|
  125. field_name = e.attribute.to_s.camelize(:lower)
  126. {
  127. field: field_name == 'base' ? nil : field_name,
  128. message: e.localized_full_message(locale: user_locale, no_field_name: true)
  129. }
  130. end
  131. end
  132. private_class_method :build_record_invalid_errors
  133. end