Skip to content

Instantly share code, notes, and snippets.

@nickpoorman
Created November 26, 2016 14:26
Show Gist options
  • Save nickpoorman/d9cbdcb44f6deaf46ae3426ef13afd9c to your computer and use it in GitHub Desktop.
Save nickpoorman/d9cbdcb44f6deaf46ae3426ef13afd9c to your computer and use it in GitHub Desktop.
# app/graph/fields/fetch_field.rb
class FetchField < GraphQL::Field
def initialize(model:, type:)
self.type = type
@model = model
self.description = 'Find a #{model.name} by ID'
self.arguments = {
'id' => GraphQL::Argument.define do
name 'id'
type !GraphQL::INT_TYPE
description 'Id for record'
end
}
end
def resolve(_object, arguments, ctx)
record = @model.find(arguments['id'])
# Pundit authorization
ctx[:pundit].authorize record, :show?
record
rescue Pundit::NotAuthorizedError
GraphQL::ExecutionError.new("Unauthorized: Show #{@model.name}")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment