-
Notifications
You must be signed in to change notification settings - Fork 32
/
memory_store.rb
65 lines (51 loc) · 1.32 KB
/
memory_store.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
# frozen_string_literal: true
using RubyNext
module GraphQL
module FragmentCache
# Memory adapter for storing cached fragments
class MemoryStore
using RubyNext
class Entry < Struct.new(:value, :expires_at, keyword_init: true)
def expired?
expires_at && expires_at < Time.now
end
end
attr_reader :default_expires_in
def initialize(expires_in: nil, **other)
raise ArgumentError, "Unsupported options: #{other.keys.join(",")}" unless other.empty?
@default_expires_in = expires_in
@storage = {}
end
def keys
storage.keys
end
def exist?(key)
storage.key?(key)
end
def read(key)
key = key.to_s
storage[key]&.then do |entry|
if entry.expired?
delete(key)
next
end
entry.value
end
end
def write(key, value, options = {})
expires_in = options[:expires_in] || default_expires_in
key = key.to_s
@storage[key] = Entry.new(value: value, expires_at: expires_in ? Time.now + expires_in : nil)
end
def delete(key)
key = key.to_s
storage.delete(key)
end
def clear
storage.clear
end
private
attr_reader :storage
end
end
end