Welcome to mirror list, hosted at ThFree Co, Russian Federation.

service_response.rb « services « app - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: c7ab75a44266c0adebcdce5f38d3ada39df49672 (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
53
54
55
56
57
58
59
60
61
62
63
64
# frozen_string_literal: true

class ServiceResponse
  def self.success(message: nil, payload: {}, http_status: :ok)
    new(status: :success, message: message, payload: payload, http_status: http_status)
  end

  def self.error(message:, payload: {}, http_status: nil)
    new(status: :error, message: message, payload: payload, http_status: http_status)
  end

  attr_reader :status, :message, :http_status, :payload

  def initialize(status:, message: nil, payload: {}, http_status: nil)
    self.status = status
    self.message = message
    self.payload = payload
    self.http_status = http_status
  end

  def track_exception(as: StandardError, **extra_data)
    if error?
      e = as.new(message)
      Gitlab::ErrorTracking.track_exception(e, extra_data)
    end

    self
  end

  def track_and_raise_exception(as: StandardError, **extra_data)
    if error?
      e = as.new(message)
      Gitlab::ErrorTracking.track_and_raise_exception(e, extra_data)
    end

    self
  end

  def [](key)
    to_h[key]
  end

  def to_h
    (payload || {}).merge(status: status, message: message, http_status: http_status)
  end

  def success?
    status == :success
  end

  def error?
    status == :error
  end

  def errors
    return [] unless error?

    Array.wrap(message)
  end

  private

  attr_writer :status, :message, :http_status, :payload
end