Resolve models and types

This commit is contained in:
Paul Chavard 2018-11-20 22:59:51 +01:00
parent e06051bc96
commit a7fc4df09b
2 changed files with 39 additions and 0 deletions

View file

@ -6,6 +6,29 @@ class Api::V2::Schema < GraphQL::Schema
query Types::QueryType
mutation Types::MutationType
def self.id_from_object(object, type_definition, ctx)
object.to_typed_id
end
def self.object_from_id(id, query_ctx)
ApplicationRecord.record_from_typed_id(id)
rescue => e
raise GraphQL::ExecutionError.new(e.message, extensions: { code: :not_found })
end
def self.resolve_type(type, obj, ctx)
case obj
when Procedure
Types::DemarcheType
when Dossier
Types::DossierType
when Instructeur, User
Types::ProfileType
else
raise GraphQL::ExecutionError.new("Unexpected object: #{obj}")
end
end
def self.unauthorized_object(error)
# Add a top-level error to the response instead of returning nil:
raise GraphQL::ExecutionError.new("An object of type #{error.type.graphql_name} was hidden due to permissions", extensions: { code: :unauthorized })

View file

@ -1,3 +1,19 @@
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
def self.record_from_typed_id(id)
class_name, record_id = GraphQL::Schema::UniqueWithinType.decode(id)
if defined?(class_name)
Object.const_get(class_name).find(record_id)
else
raise ActiveRecord::RecordNotFound, "Unexpected object: #{class_name}"
end
rescue => e
raise ActiveRecord::RecordNotFound, e.message
end
def to_typed_id
GraphQL::Schema::UniqueWithinType.encode(self.class.name, id)
end
end