Allow custom cache expiry

This commit is contained in:
2024-02-11 14:40:11 +11:00
parent 081de8b98e
commit d83dac92a5
3 changed files with 8 additions and 6 deletions

View File

@@ -22,8 +22,8 @@ module Adamantium
handle_exception ROM::TupleCountMismatchError => :not_found handle_exception ROM::TupleCountMismatchError => :not_found
handle_exception StandardError => :handle_error handle_exception StandardError => :handle_error
def cache(key:, content:) def cache(key:, content_proc:, expiry: TimeMath.min.advance(Time.now, +10))
cacher.call(key: key, content: content, expiry: TimeMath.min.advance(Time.now, +10)) cacher.call(key: key, content_proc: content_proc, expiry: expiry)
end end
def not_found(_req, res, _exception) def not_found(_req, res, _exception)

View File

@@ -7,7 +7,7 @@ module Adamantium
include Deps["views.recently_played.index"] include Deps["views.recently_played.index"]
def handle(req, res) def handle(req, res)
res.body = cache(key: "recently_played", content: index.call.to_str) res.body = cache(key: "recently_played", content_proc: -> { index.call.to_str })
end end
end end
end end

View File

@@ -3,18 +3,20 @@ require "json"
module Adamantium module Adamantium
module ViewCache module ViewCache
class Cacher class Cacher
def call(key:, content:, expiry:) def call(key:, content_proc:, expiry:)
cached_content = read(key: key) cached_content = read(key: key)
return cached_content if cached_content return cached_content if cached_content
data = JSON.generate(expire: expiry.to_i, content: content) rendered_content = content_proc.()
data = JSON.generate(expire: expiry.to_i, content: rendered_content)
path = "#{key}.json" path = "#{key}.json"
File.write(File.join(Hanami.app.root, "tmp", path), data) File.write(File.join(Hanami.app.root, "tmp", path), data)
content rendered_content
end end
private private