2019-04-19 11:39:12 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
class ServiceResponse
|
2019-09-16 08:06:26 -04:00
|
|
|
def self.success(message: nil, payload: {}, http_status: :ok)
|
|
|
|
new(status: :success, message: message, payload: payload, http_status: http_status)
|
2019-04-19 11:39:12 -04:00
|
|
|
end
|
|
|
|
|
2019-05-21 17:14:22 -04:00
|
|
|
def self.error(message:, payload: {}, http_status: nil)
|
|
|
|
new(status: :error, message: message, payload: payload, http_status: http_status)
|
2019-04-19 11:39:12 -04:00
|
|
|
end
|
|
|
|
|
2019-05-21 17:14:22 -04:00
|
|
|
attr_reader :status, :message, :http_status, :payload
|
2019-04-19 11:39:12 -04:00
|
|
|
|
2019-05-21 17:14:22 -04:00
|
|
|
def initialize(status:, message: nil, payload: {}, http_status: nil)
|
2019-04-19 11:39:12 -04:00
|
|
|
self.status = status
|
|
|
|
self.message = message
|
2019-05-21 17:14:22 -04:00
|
|
|
self.payload = payload
|
2019-04-19 11:39:12 -04:00
|
|
|
self.http_status = http_status
|
|
|
|
end
|
|
|
|
|
2021-05-01 17:09:45 -04:00
|
|
|
def [](key)
|
|
|
|
to_h[key]
|
|
|
|
end
|
|
|
|
|
|
|
|
def to_h
|
|
|
|
(payload || {}).merge(status: status, message: message, http_status: http_status)
|
|
|
|
end
|
|
|
|
|
2019-04-19 11:39:12 -04:00
|
|
|
def success?
|
|
|
|
status == :success
|
|
|
|
end
|
|
|
|
|
|
|
|
def error?
|
|
|
|
status == :error
|
|
|
|
end
|
|
|
|
|
2020-06-08 11:08:20 -04:00
|
|
|
def errors
|
|
|
|
return [] unless error?
|
|
|
|
|
|
|
|
Array.wrap(message)
|
|
|
|
end
|
|
|
|
|
2019-04-19 11:39:12 -04:00
|
|
|
private
|
|
|
|
|
2019-05-21 17:14:22 -04:00
|
|
|
attr_writer :status, :message, :http_status, :payload
|
2019-04-19 11:39:12 -04:00
|
|
|
end
|