Skip to content

Instantly share code, notes, and snippets.

@msroot
msroot / base_connection.rb
Last active April 28, 2020 13:13
add total_count to all connections
class Types::BaseConnection < GraphQL::Types::Relay::BaseConnection
field :total_count, Integer, null: false
def total_count
object.items.size
end
end
@msroot
msroot / initializers_graphql.rb
Created April 28, 2020 12:49 — forked from theorygeek/initializers_graphql.rb
GraphQL Connection Counts
# Monkey Patch: Add a count field to all connections by default.
# Note, I tried to make this nicer, where it would just call the original method and then add a count field,
# but the challenge outlasted my patience. So I just replaced the whole method. TODO: better way to do this
module GraphQL
module Relay
module ConnectionType
def self.create_type(wrapped_type, edge_type: wrapped_type.edge_type, edge_class: GraphQL::Relay::Edge, nodes_field: ConnectionType.default_nodes_field, &block)
custom_edge_class = edge_class
# Any call that would trigger `wrapped_type.ensure_defined`
# Define an instrumentation that performs the caching
class CachingInstrumentation
def instrument(_type, field)
return field unless field.metadata.include?(:cache_proc)
old_resolver = field.resolve_proc
new_resolver = -> (obj, args, ctx) do
# Get the caching key
cache_key = field.metadata[:cache_proc].call(obj, args, ctx)
# Define an instrumentation that performs the caching
class CachingInstrumentation
def instrument(_type, field)
return field unless field.metadata.include?(:cache_proc)
old_resolver = field.resolve_proc
new_resolver = -> (obj, args, ctx) do
# Get the caching key
cache_key = field.metadata[:cache_proc].call(obj, args, ctx)
module Resolvers
class UsersResolver < Resolvers::BaseSearchResolver
create_connection_for(User)
end
end
require 'search_object'
require 'search_object/plugin/graphql'
module Resolvers
class BaseSearchResolver
include ::SearchObject.module(:graphql)
def self.create_connection_for(klass)
plural = ActiveSupport::Inflector.pluralize(klass.to_s)
module Resolvers
class UsersResolver < Resolvers::BaseSearchResolver
type Types::UserType.connection_type, null: false
scope { object.respond_to?(:users) ? object.users : User.none }
end
end
module Resolvers
class UsersResolver < Resolvers::BaseSearchResolver
type Types::UserType.connection_type, null: false
scope { context[:current_user].admin? ? User.all : User.none }
end
end
@msroot
msroot / user.rb
Last active April 27, 2020 17:17
class User < ApplicationRecord
searchkick
def search_data
attributes.slice(*%w[first_name last_name email])
end
end
module Types
class QueryType < Types::BaseObject
field :users, resolver: Resolvers::UsersResolver
end
end