Last active
September 5, 2017 14:40
-
-
Save lunks/2656b5000b328316f715d7b30ee117ac to your computer and use it in GitHub Desktop.
GraphQL resolver example with tests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Resolvers | |
class CreateEvent | |
include Pundit | |
def self.call(*args) | |
new(*args).resolve | |
end | |
attr_reader :current_user | |
def initialize(_obj, args, ctx) | |
@organization_id = args[:organizationId] | |
@current_user = ctx[:current_user] | |
@params = args[:input].to_h.with_indifferent_access | |
@questions = @params.delete(:questions) || [] | |
end | |
def resolve | |
raise Pundit::NotAuthorizedError if current_user.blank? || !authorized? | |
build_questions | |
if event.save | |
event | |
else | |
GraphQL::ExecutionError.new(@event.errors.details.to_json) | |
end | |
end | |
private | |
def authorized? | |
authorize event, :create? | |
end | |
def organization | |
::Organization.find(@organization_id) | |
end | |
def build_questions | |
@questions.each do |question| | |
event.questions.build(question) | |
end | |
end | |
def event | |
@event ||= organization.events.build(@params) | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rails_helper' | |
RSpec.describe Resolvers::CreateEvent do | |
describe 'resolve create event mutation' do | |
let!(:organization) { create(:organization) } | |
let!(:args) do | |
{ | |
organizationId: organization.id, | |
input: attributes_for(:event) | |
} | |
end | |
let(:user) { create(:user) } | |
let(:context) { { current_user: user } } | |
context 'when an user has access to the organization' do | |
before { organization.users << user } | |
context 'with questions' do | |
let!(:args) do | |
{ | |
organizationId: organization.id, | |
input: attributes_for(:event).merge( | |
questions: [ | |
{ title: 'How well were you treated?', question_type: :rating } | |
] | |
) | |
} | |
end | |
it 'creates a new event' do | |
described_class.call(nil, args, context) | |
expect(organization.events.count).to eq 1 | |
event = organization.events.first | |
expect(event.questions.count).to eq 1 | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment