Skip to content

Instantly share code, notes, and snippets.

@nickpoorman
Created November 26, 2016 14:22
Show Gist options
  • Save nickpoorman/0f90dc9ef84f476afe79a4b47485cb01 to your computer and use it in GitHub Desktop.
Save nickpoorman/0f90dc9ef84f476afe79a4b47485cb01 to your computer and use it in GitHub Desktop.
# app/graph/application_schema.rb
ApplicationSchema = GraphQL::Schema.define do
query QueryType
mutation MutationType
resolve_type -> (object, _ctx) { ApplicationSchema.types[object.class.name] }
# These are used by relay
object_from_id -> (id, ctx) { decode_object(id, ctx) }
id_from_object -> (obj, type, ctx) { encode_object(obj, type, ctx) }
rescue_from ActiveRecord::RecordInvalid, &:message
rescue_from ActiveRecord::Rollback, &:message
rescue_from StandardError, &:message
rescue_from ActiveRecord::RecordNotUnique, &:message
rescue_from ActiveRecord::RecordNotFound, &:message
def encode_object(object, type, _ctx)
GraphQL::Schema::UniqueWithinType.encode(type.name, object.id)
end
def decode_object(id, ctx)
type_name, record_id = GraphQL::Schema::UniqueWithinType.decode(id)
# This `find` gives the user unrestricted access to *all* the records in the app. That's
# why below we check if the user is allowed to access the requested resource via Pundit.
record = type_name.constantize.find(record_id)
# Pundit authorization
ctx[:pundit].authorize record, :show?
record
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment