Sha256: 4331a82de4811a7a560cebacbb96f5b161afd8a1de6af289a16c339d71e576d4

Contents?: true

Size: 1.44 KB

Versions: 1

Compression:

Stored size: 1.44 KB

Contents

# frozen_string_literal: true

module Dexcom
  module BloodGlucoseUtils
    module ApiHandler
      MAX_MINUTES = 1440

      def make_api_request(number_of_values)
        HTTParty.post(
          endpoint,
          headers: headers,
          query: query(number_of_values)
        )
      end

      def process_api_response(response)
        response_body = JSON.parse(response.body)

        response_body.map { |blood_glucose_item| build_from_api_response(blood_glucose_item) }
      end

      def build_from_api_response(blood_glucose_response_item)
        Dexcom::BloodGlucose.new(
          blood_glucose_response_item['Value'],
          blood_glucose_response_item['Trend'],
          parse_timestamp(blood_glucose_response_item)
        )
      end

      private

      def endpoint
        "#{config.base_url}/Publisher/ReadPublisherLatestGlucoseValues"
      end

      def headers
        {
          'User-Agent' => USER_AGENT
        }
      end

      def query(max_count)
        {
          maxCount: max_count,
          minutes: MAX_MINUTES
        }
      end

      def parse_timestamp(blood_glucose_response_item)
        timestamp_info = blood_glucose_response_item['WT']
        timestamp_regex = /(\d+)000/
        timestamp = timestamp_info[timestamp_regex, 1]
        utc = '+00:00'

        DateTime.parse(Time.at(timestamp.to_i, in: utc).to_s)
      end

      def config
        @config ||= Dexcom.configuration
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
dexcom-0.2.0 lib/dexcom/blood_glucose/api_handler.rb