Sha256: c716af3362cfb3155d017028e3778e8bcf178ee9137710dc64ca2029938a16c3

Contents?: true

Size: 965 Bytes

Versions: 1

Compression:

Stored size: 965 Bytes

Contents

# frozen_string_literal: true

require 'json'

module WaCloudApi
  module Message
    class Response
      Contact = Struct.new(:input, :wa_id, keyword_init: true)
      Message = Struct.new(:id, keyword_init: true)

      attr_accessor :status, :data

      def initialize(status, response)
        @status = status.to_i
        @data = convert_keys_to_symbols(JSON.parse(response))
      end

      def ok?
        status == 200
      end

      def contacts
        data[:contacts]&.map(&Contact.method(:new)) || []
      end

      def messages
        data[:messages]&.map(&Message.method(:new)) || []
      end

      private

      def convert_keys_to_symbols(obj)
        case obj
        when Hash
          obj.transform_keys(&:to_sym)
             .transform_values { |value| convert_keys_to_symbols(value) }
        when Array
          obj.map { |item| convert_keys_to_symbols(item) }
        else
          obj
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
wa_cloud_api-0.1.1 lib/wa_cloud_api/message/response.rb