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, version) ⇒ SqliteStore

Returns a new instance of SqliteStore.

Raises:

  • (ArgumentError)


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

def initialize(path, version)
  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)
  raise ArgumentError, 'Version cannot be nil or empty' if version.nil? || version.empty?
  @path = File.absolute_path(path)
  @version = version
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



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

def path
  @path
end

Instance Method Details

#allObject



66
67
68
# File 'lib/fbe/middleware/sqlite_store.rb', line 66

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

#clearObject



58
59
60
61
62
63
64
# File 'lib/fbe/middleware/sqlite_store.rb', line 58

def clear
  perform do |t|
    t.execute 'DELETE FROM cache;'
    t.execute "UPDATE meta SET value = ? WHERE key = 'version';", [@version]
  end
  @db.execute 'VACUUM;'
end

#delete(key) ⇒ Object



37
38
39
40
# File 'lib/fbe/middleware/sqlite_store.rb', line 37

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

#read(key) ⇒ Object



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

def read(key)
  value = perform do |t|
    t.execute('UPDATE cache SET touched_at = ?2 WHERE key = ?1;', [key, Time.now.utc.iso8601])
    t.execute('SELECT value FROM cache WHERE key = ? LIMIT 1;', [key])
  end.dig(0, 0)
  JSON.parse(value) if value
end

#write(key, value) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/fbe/middleware/sqlite_store.rb', line 42

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)
  return if value.bytesize > 10_000
  perform do |t|
    t.execute("      INSERT INTO cache(key, value, touched_at) VALUES(?1, ?2, ?3)\n      ON CONFLICT(key) DO UPDATE SET value = ?2, touched_at = ?3\n    SQL\n  end\n  nil\nend\n", [key, value, Time.now.utc.iso8601])