summaryrefslogtreecommitdiff
path: root/app/services/base_count_service.rb
blob: ff1949ce4dd83459d0f04330f1b08f16af054d2c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# frozen_string_literal: true

# Base class for services that count a single resource such as the number of
# issues for a project.
class BaseCountService
  def relation_for_count
    raise(
      NotImplementedError,
      '"relation_for_count" must be implemented and return an ActiveRecord::Relation'
    )
  end

  def count
    Rails.cache.fetch(cache_key, cache_options) { uncached_count }.to_i
  end

  def count_stored?
    Rails.cache.read(cache_key).present?
  end

  def refresh_cache(&block)
    update_cache_for_key(cache_key, &block)
  end

  def uncached_count
    relation_for_count.count
  end

  def delete_cache
    ::Gitlab::Cache.delete(cache_key)
  end

  def raw?
    false
  end

  def cache_key
    raise NotImplementedError, 'cache_key must be implemented and return a String, Array, or Hash'
  end

  # subclasses can override to add any specific options, such as
  #   super.merge({ expires_in: 5.minutes })
  def cache_options
    { raw: raw? }
  end

  def update_cache_for_key(key, &block)
    Rails.cache.write(key, block_given? ? yield : uncached_count, raw: raw?)
  end
end

BaseCountService.prepend_mod