-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathactive_record_relation_connection.rb
77 lines (68 loc) · 1.78 KB
/
active_record_relation_connection.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# frozen_string_literal: true
require "graphql/pagination/relation_connection"
module GraphQL
module Pagination
# Customizes `RelationConnection` to work with `ActiveRecord::Relation`s.
class ActiveRecordRelationConnection < Pagination::RelationConnection
private
def relation_count(relation)
int_or_hash = if already_loaded?(relation)
relation.size
elsif relation.respond_to?(:unscope)
relation.unscope(:order).count(:all)
else
# Rails 3
relation.count
end
if int_or_hash.is_a?(Integer)
int_or_hash
else
# Grouped relations return count-by-group hashes
int_or_hash.length
end
end
def relation_limit(relation)
if relation.is_a?(Array)
nil
else
relation.limit_value
end
end
def relation_offset(relation)
if relation.is_a?(Array)
nil
else
relation.offset_value
end
end
def null_relation(relation)
if relation.respond_to?(:none)
relation.none
else
# Rails 3
relation.where("1=2")
end
end
def set_limit(nodes, limit)
if already_loaded?(nodes)
nodes.take(limit)
else
super
end
end
def set_offset(nodes, offset)
if already_loaded?(nodes)
# If the client sent a bogus cursor beyond the size of the relation,
# it might get `nil` from `#[...]`, so return an empty array in that case
nodes[offset..-1] || []
else
super
end
end
private
def already_loaded?(relation)
relation.is_a?(Array) || relation.loaded?
end
end
end
end