You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

34 lines
1.2 KiB

  1. # frozen_string_literal: true
  2. require 'singleton'
  3. class EntityCache
  4. include Singleton
  5. MAX_EXPIRATION = 7.days.freeze
  6. def mention(username, domain)
  7. Rails.cache.fetch(to_key(:mention, username, domain), expires_in: MAX_EXPIRATION) { Account.select(:username, :domain, :url).find_remote(username, domain) }
  8. end
  9. def emoji(shortcodes, domain)
  10. shortcodes = [shortcodes] unless shortcodes.is_a?(Array)
  11. cached = Rails.cache.read_multi(*shortcodes.map { |shortcode| to_key(:emoji, shortcode, domain) })
  12. uncached_ids = []
  13. shortcodes.each do |shortcode|
  14. uncached_ids << shortcode unless cached.key?(to_key(:emoji, shortcode, domain))
  15. end
  16. unless uncached_ids.empty?
  17. uncached = CustomEmoji.where(shortcode: shortcodes, domain: domain, disabled: false).map { |item| [item.shortcode, item] }.to_h
  18. uncached.each_value { |item| Rails.cache.write(to_key(:emoji, item.shortcode, domain), item, expires_in: MAX_EXPIRATION) }
  19. end
  20. shortcodes.map { |shortcode| cached[to_key(:emoji, shortcode, domain)] || uncached[shortcode] }.compact
  21. end
  22. def to_key(type, *ids)
  23. "#{type}:#{ids.compact.map(&:downcase).join(':')}"
  24. end
  25. end