58 lines
1.3 KiB
Ruby
Raw Normal View History

2024-12-07 18:40:23 +01:00
# frozen_string_literal: true
module DiscourseRewind
# Service responsible to fetch a rewind for a username/year.
#
# @example
# ::DiscourseRewind::Rewind::Fetch.call(
2024-12-13 17:00:17 +01:00
# guardian: guardian
2024-12-07 18:40:23 +01:00
# )
#
class Rewind::Fetch
include Service::Base
# @!method self.call(guardian:, params:)
# @param [Guardian] guardian
# @param [Hash] params
# @option params [Integer] :year of the rewind
# @option params [Integer] :username of the rewind
# @return [Service::Base::Context]
CACHE_DURATION = 5.minutes
2024-12-13 17:00:17 +01:00
YEAR = 2024
2024-12-07 18:40:23 +01:00
2024-12-11 22:38:58 +01:00
model :user
model :date
2024-12-07 18:40:23 +01:00
model :reports
private
2024-12-13 17:00:17 +01:00
def fetch_user(guardian:)
User.find_by_username(guardian.user.username)
2024-12-11 22:38:58 +01:00
end
def fetch_date(params:)
2024-12-13 17:00:17 +01:00
Date.new(YEAR).all_year
2024-12-11 22:38:58 +01:00
end
2024-12-13 17:00:17 +01:00
def fetch_reports(date:, user:, guardian:)
key = "rewind:#{guardian.user.username}:#{YEAR}"
2024-12-07 18:40:23 +01:00
reports = Discourse.redis.get(key)
if Rails.env.development? || !reports
2024-12-12 17:45:22 -03:00
reports =
2024-12-13 17:00:17 +01:00
::DiscourseRewind::Rewind::Action::BaseReport
.descendants
2024-12-12 17:45:22 -03:00
.filter { _1.enabled? }
2024-12-13 17:00:17 +01:00
.map { |report| report.call(date:, user:, guardian:) }
2024-12-07 18:40:23 +01:00
Discourse.redis.setex(key, CACHE_DURATION, MultiJson.dump(reports))
else
2024-12-11 22:38:44 +01:00
reports = MultiJson.load(reports, symbolize_keys: true)
2024-12-07 18:40:23 +01:00
end
reports
end
end
end