Skip to content

Commit

Permalink
Add PreloadExtension
Browse files Browse the repository at this point in the history
  • Loading branch information
vivekmiyani committed Jun 14, 2024
1 parent 999fa11 commit aafe132
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 25 deletions.
5 changes: 4 additions & 1 deletion lib/phantom/graphql.rb
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
# frozen_string_literal: true

require "graphql"
require "batch-loader"

module Phantom::Graphql
end

require "phantom/graphql/authorization"
require "phantom/graphql/field_extensions"
require "phantom/graphql/enum"
require "phantom/graphql/response"

GraphQL::Schema.use(BatchLoader::GraphQL)

GraphQL::Schema::InputObject.extend(Phantom::Graphql::Enum)
GraphQL::Schema::Object.extend(Phantom::Graphql::Enum)
GraphQL::Schema::RelayClassicMutation.extend(Phantom::Graphql::Enum)
Expand Down
23 changes: 0 additions & 23 deletions lib/phantom/graphql/authorization.rb

This file was deleted.

34 changes: 34 additions & 0 deletions lib/phantom/graphql/field_extensions.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# frozen_string_literal: true

module Phantom::Graphql::FieldExtensions
class AuthorizeExtension < GraphQL::Schema::FieldExtension
def resolve(context:, object:, arguments:, **_rest)
name, action = options.split("#")

authorized = name.constantize.new(context[:current_session]).send(action)

raise GraphQL::ExecutionError, "Unauthorized" unless authorized

yield object, arguments
end
end

class PreloadExtension < GraphQL::Schema::FieldExtension
def resolve(context:, object:, arguments:, **rest)
BatchLoader::GraphQL.for(object).batch(key: field) do |records, loader|
scope = options[:scope].constantize.new(context[:current_session]).scope if options[:scope].present?
ActiveRecord::Associations::Preloader.new(records: records.map(&:object), associations: options[:preload]).call
records.each { |r| loader.call(r, super(context: context, object: r, arguments: arguments, **rest)) }
end
end
end

def initialize(*args, authorize: nil, preload: nil, scope: nil, **kwargs, &block)
extensions = (kwargs[:extensions] ||= [])

extensions << { Phantom::Graphql::FieldExtensions::AuthorizeExtension => authorize } if authorize.present?
extensions << { Phantom::Graphql::FieldExtensions::PreloadExtension => { preload: preload, scope: scope } } if preload.present?

super(*args, **kwargs, &block)
end
end
2 changes: 1 addition & 1 deletion phantom.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,6 @@ Gem::Specification.new do |s|
s.metadata["rubygems_mfa_required"] = "true"

s.required_ruby_version = ">= 3.1"
s.add_dependency "batch-loader"
s.add_dependency "graphql"
s.add_dependency "minitest"
end

0 comments on commit aafe132

Please sign in to comment.