Sha256: ee3ae0588e04a6ab063a9432277905fcce934642f42387a68e09c1e04653f602

Contents?: true

Size: 1.46 KB

Versions: 1

Compression:

Stored size: 1.46 KB

Contents

# frozen_string_literal: true

require 'json'
require "net/http"
require "uri"

module GoogleAnalyticsV4Api
  class Client

    BASE_URL = "https://analyticsadmin.googleapis.com/v1beta"

    def initialize(access_token)
      @access_token = access_token
    end

    def accounts
      @accounts ||= GoogleAnalyticsV4Api::Account.parse_list get("/accounts").body
    end

    def account(account_name)
      accounts.find { |account| account.name == account_name }
    end

    def properties(account_name)
      @properties ||= GoogleAnalyticsV4Api::Property.parse_list get("/properties", { filter: "parent:#{account_name}"}).body
    end

    def property(property_name)
      unless @properties.nil?
        property = @properties.find { |property| property.name == property_name }
        return property unless property.nil?
      end

      GoogleAnalyticsV4Api::Property.parse get("/#{property_name}").body
    end

    private
    def get(path, params = {})
      url = "#{BASE_URL}#{path}"
      url += "?#{URI.encode_www_form params}" unless params.empty?
      uri = URI(url)

      response = Net::HTTP.start(uri.host, uri.port, :use_ssl => true) do |http|
        request = Net::HTTP::Get.new uri
        request["Authorization"] = "Bearer #{@access_token}"
        request["Content-Type"] = "application/json"

        http.request request
      end
      raise GoogleAnalyticsV4Api::Error.new(response) unless response.is_a?(Net::HTTPSuccess)

      response
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
google_analytics_v4_api-0.0.1 lib/google_analytics_v4_api/client.rb