Class: Fbe::Middleware::SqliteStore

Inherits:
Object
  • Object
show all
Defined in:
lib/fbe/middleware/sqlite_store.rb

Overview

Persisted SQLite store for Faraday::HttpCache

Author

Yegor Bugayenko ([email protected])

Copyright

Copyright © 2024-2025 Zerocracy

License

MIT

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ SqliteStore

Returns a new instance of SqliteStore.

Raises:

  • (ArgumentError)


19
20
21
22
23
24
# File 'lib/fbe/middleware/sqlite_store.rb', line 19

def initialize(path)
  raise ArgumentError, 'Database path cannot be nil or empty' if path.nil? || path.empty?
  dir = File.dirname(path)
  raise ArgumentError, "Directory #{dir} does not exist" unless File.directory?(dir)
  @path = File.absolute_path(path)
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



17
18
19
# File 'lib/fbe/middleware/sqlite_store.rb', line 17

def path
  @path
end

Instance Method Details

#allObject



55
56
57
# File 'lib/fbe/middleware/sqlite_store.rb', line 55

def all
  perform { _1.execute('SELECT key, value FROM cache') }
end

#clearObject



51
52
53
# File 'lib/fbe/middleware/sqlite_store.rb', line 51

def clear
  perform { _1.execute 'DELETE FROM cache;' }
end

#delete(key) ⇒ Object



31
32
33
34
# File 'lib/fbe/middleware/sqlite_store.rb', line 31

def delete(key)
  perform { _1.execute('DELETE FROM cache WHERE key = ?', [key]) }
  nil
end

#read(key) ⇒ Object



26
27
28
29
# File 'lib/fbe/middleware/sqlite_store.rb', line 26

def read(key)
  value = perform { _1.execute('SELECT value FROM cache WHERE key = ? LIMIT 1', [key]) }.dig(0, 0)
  JSON.parse(value) if value
end

#write(key, value) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/fbe/middleware/sqlite_store.rb', line 36

def write(key, value)
  return if value.is_a?(Array) && value.any? do |vv|
    req = JSON.parse(vv[0])
    req['url'].include?('?') || req['method'] != 'get'
  end
  value = JSON.dump(value)
  perform do |t|
    t.execute("      INSERT INTO cache(key, value) VALUES(?1, ?2)\n      ON CONFLICT(key) DO UPDATE SET value = ?2\n    SQL\n  end\n  nil\nend\n", [key, value])