forked from FabienChaynes/mongoid-scroll
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbase64_encoded_cursor.rb
42 lines (40 loc) · 1.39 KB
/
base64_encoded_cursor.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
require 'base64'
require 'json'
module Mongoid
module Scroll
# Allows to serializer/deserialize the cursor using RFC 4648
class Base64EncodedCursor < BaseCursor
def initialize(value, options = {})
options = extract_field_options(options)
if value
begin
parsed = ::JSON.parse(::Base64.strict_decode64(value))
rescue
raise Mongoid::Scroll::Errors::InvalidBase64CursorError.new(cursor: value)
end
super parse_field_value(parsed['field_type'], parsed['field_name'], parsed['value']), {
field_type: parsed['field_type'],
field_name: parsed['field_name'],
direction: parsed['direction'],
include_current: parsed['include_current'],
tiebreak_id: parsed['tiebreak_id'] && !parsed['tiebreak_id'].empty? ? BSON::ObjectId.from_string(parsed['tiebreak_id']) : nil,
type: parsed['type'].try(:to_sym)
}
else
super nil, options
end
end
def to_s
Base64.strict_encode64({
value: transform_field_value(field_type, field_name, value),
field_type: field_type.to_s,
field_name: field_name,
direction: direction,
include_current: include_current,
tiebreak_id: tiebreak_id && tiebreak_id.to_s,
type: type
}.to_json)
end
end
end
end