Sha256: 3d4aba8a180d44d7b4eb36ebcaa76e387ced43e8a1585313ab1d2d497c8e2b30

Contents?: true

Size: 1.46 KB

Versions: 5

Compression:

Stored size: 1.46 KB

Contents

# frozen_string_literal: true

require "httparty"

module Songstats
  module Api
    # Base class for the Songstats API
    class Base
      include HTTParty

      SONG_STATS_ID_LENGTH = 8
      ISRC_LENGTH = 12

      base_uri "https://api.songstats.com/enterprise/v1"

      def initialize
        @api_key = ENV.fetch "SONGSTATS_API_KEY", nil

        raise "Missing SongStats API key" if @api_key.nil?
      end

      private

      def path(id, path, options = {})
        path += case id.size
                when ISRC_LENGTH
                  "?isrc=#{id}"
                when SONG_STATS_ID_LENGTH
                  "?songstats_#{@type}_id=#{id}"
                else
                  "?spotify_#{@type}_id=#{id}"
                end
        options.each { |key, value| path += "&#{key}=#{value}" }
        path
      end

      def fetch(path)
        response = self.class.get path, headers: { "apiKey" => @api_key }
        return response.parsed_response if response.success?

        raise response.parsed_response
      end

      def post(path, body)
        response = self.class.post path, body: body, headers: { "apiKey" => @api_key }
        return response.parsed_response if response.success?

        raise response.parsed_response
      end

      def delete(path)
        response = self.class.delete path, headers: { "apiKey" => @api_key }
        return response.parsed_response if response.success?

        raise response.parsed_response
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
songstats-api-1.0.0 lib/songstats/api/base.rb
songstats-api-0.1.6 lib/songstats/api/base.rb
songstats-api-0.1.4 lib/songstats/api/base.rb
songstats-api-0.1.2 lib/songstats/api/base.rb
songstats-api-0.1.1 lib/songstats/api/base.rb