From 9185a0a3dc132437f91cf14b18fe5510ba056e52 Mon Sep 17 00:00:00 2001 From: Xero Date: Wed, 28 Feb 2024 12:57:57 -0500 Subject: [PATCH] base most client impemention --- lib/plants.rb | 2 ++ lib/plants/client.rb | 40 ++++++++++++++++++++++++++++++++++++++ spec/plants/client_spec.rb | 36 ++++++++++++++++++++++++++++++++++ 3 files changed, 78 insertions(+) create mode 100644 lib/plants/client.rb create mode 100644 spec/plants/client_spec.rb diff --git a/lib/plants.rb b/lib/plants.rb index 71d831d..3b93971 100644 --- a/lib/plants.rb +++ b/lib/plants.rb @@ -1,5 +1,7 @@ # frozen_string_literal: true +require "plants/client" +require "plants/config" require "plants/version" module Plants diff --git a/lib/plants/client.rb b/lib/plants/client.rb new file mode 100644 index 0000000..b7f2018 --- /dev/null +++ b/lib/plants/client.rb @@ -0,0 +1,40 @@ +# frozen_string_literal: true +require 'http' + +require 'plants/version' + +module Plants + # HTTP Client + # + # @!attribute [r] config + # @return [Plants::Config] + # + class Client + # Trefle API URL + URL = "https://trefle.io/api/v1".freeze + + # @param config [Plants::Config] + def initialize(config) + @config = config + end + attr_reader :config + + + # @param resource [String] + # @param params [Hash] + # @return [HTTP::Response] + def get(resource, params: {}) + params.merge({ token: config.token }) if config.token.is_a?(String) + http.get("#{URL}/#{resource}", params: params) + end + + private + + # @return [HTTP::Client] + def http + HTTP + .timeout(5) + .headers({ 'User-Agent' => "Plants #{Plants::VERSION} ruby-#{RUBY_VERSION}" }) + end + end +end \ No newline at end of file diff --git a/spec/plants/client_spec.rb b/spec/plants/client_spec.rb new file mode 100644 index 0000000..c1d52a9 --- /dev/null +++ b/spec/plants/client_spec.rb @@ -0,0 +1,36 @@ +RSpec.describe Plants::Client do + let(:config) { instance_double(Plants::Config) } + let(:client) { Plants::Client.new(config) } + + describe '.new' do + subject { client } + + it do + expect(subject).to be_instance_of(Plants::Client) + end + end + + describe '#config' do + subject { client.config } + + it do + expect(subject).to be(config) + end + end + + describe '#get' do + context 'resource = plants' do + subject { client.get 'plants' } + + before(:each) do + stub_request(:get, "#{Plants::Client::URL}/plants").to_return(status: 200, body: '{}') + end + + it do + expect(config).to receive(:token).and_return(nil) + expect(subject).to be_instance_of(HTTP::Response) + expect(a_request(:get, "#{Plants::Client::URL}/plants")).to have_been_made + end + end + end +end \ No newline at end of file