From 2ec24eeb3f11a6892e709210a66afbcc94bcde66 Mon Sep 17 00:00:00 2001 From: hanswys Date: Tue, 15 Sep 2026 14:37:25 +0800 Subject: [PATCH 1/2] Scaffold Rails-independent Hive API gem --- .github/workflows/ci.yml | 18 ++++++ .gitignore | 11 ++++ .rspec | 2 + .standard.yml | 1 + .tool-versions | 1 + CHANGELOG.md | 9 +++ Gemfile | 5 ++ LICENSE.txt | 21 ++++++ README.md | 68 +++++++++++++++++++- Rakefile | 10 +++ hive_api.gemspec | 32 +++++++++ lib/hive_api.rb | 14 ++++ lib/hive_api/client.rb | 52 +++++++++++++++ lib/hive_api/errors.rb | 7 ++ lib/hive_api/object.rb | 71 ++++++++++++++++++++ lib/hive_api/resource.rb | 35 ++++++++++ lib/hive_api/version.rb | 5 ++ spec/gemspec_spec.rb | 29 +++++++++ spec/hive_api/client_spec.rb | 114 +++++++++++++++++++++++++++++++++ spec/hive_api/object_spec.rb | 80 +++++++++++++++++++++++ spec/hive_api/resource_spec.rb | 75 ++++++++++++++++++++++ spec/hive_api_spec.rb | 49 ++++++++++++++ spec/spec_helper.rb | 22 +++++++ 23 files changed, 730 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/ci.yml create mode 100644 .gitignore create mode 100644 .rspec create mode 100644 .standard.yml create mode 100644 .tool-versions create mode 100644 CHANGELOG.md create mode 100644 Gemfile create mode 100644 LICENSE.txt create mode 100644 Rakefile create mode 100644 hive_api.gemspec create mode 100644 lib/hive_api.rb create mode 100644 lib/hive_api/client.rb create mode 100644 lib/hive_api/errors.rb create mode 100644 lib/hive_api/object.rb create mode 100644 lib/hive_api/resource.rb create mode 100644 lib/hive_api/version.rb create mode 100644 spec/gemspec_spec.rb create mode 100644 spec/hive_api/client_spec.rb create mode 100644 spec/hive_api/object_spec.rb create mode 100644 spec/hive_api/resource_spec.rb create mode 100644 spec/hive_api_spec.rb create mode 100644 spec/spec_helper.rb diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..f9c272d --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,18 @@ +name: CI + +on: + push: + pull_request: + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: ruby/setup-ruby@v1 + with: + ruby-version: "3.3.9" + bundler-cache: true + - run: bundle exec rake + - run: bundle exec ruby -Ilib -e 'require "hive_api"; HiveAPI::Client; HiveAPI::Base; HiveAPI::Resource; HiveAPI::Error; HiveAPI::APIError; abort "Rails loaded" if defined?(Rails); abort "Zeitwerk loaded" if defined?(Zeitwerk)' + - run: gem build hive_api.gemspec diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..301c2ad --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +/.bundle/ +/.yardoc +/_yardoc/ +/coverage/ +/doc/ +/pkg/ +/spec/reports/ +/tmp/ +*.gem +Gemfile.lock +.env diff --git a/.rspec b/.rspec new file mode 100644 index 0000000..5be63fc --- /dev/null +++ b/.rspec @@ -0,0 +1,2 @@ +--require spec_helper +--format documentation diff --git a/.standard.yml b/.standard.yml new file mode 100644 index 0000000..49bff5f --- /dev/null +++ b/.standard.yml @@ -0,0 +1 @@ +ruby_version: 3.3 diff --git a/.tool-versions b/.tool-versions new file mode 100644 index 0000000..773d7a5 --- /dev/null +++ b/.tool-versions @@ -0,0 +1 @@ +ruby 3.3.9 diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..36c6a9a --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,9 @@ +# Changelog + +## [Unreleased] + +### Added + +- Rails-independent Hive API client foundation with fixed production, staging, and official mock environments. +- Bounded Faraday connections with injectable adapters and safe JSON middleware. +- Shared resource and response-object foundations. diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..be173b2 --- /dev/null +++ b/Gemfile @@ -0,0 +1,5 @@ +# frozen_string_literal: true + +source "https://rubygems.org" + +gemspec diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..9b8f622 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2026 PostCo + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/README.md b/README.md index f10daa5..4444290 100644 --- a/README.md +++ b/README.md @@ -1 +1,67 @@ -# hive_api \ No newline at end of file +# HiveAPI + +Rails-independent Ruby client foundation for the [Hive Merchant API](https://developers.hive.app/). + +## Installation + +Add the gem to your Gemfile: + +```ruby +gem "hive_api", "~> 0.1.0" +``` + +Then run `bundle install`. + +## Usage + +Require the gem and select one of Hive's fixed API environments when building a client: + +```ruby +require "hive_api" + +client = HiveAPI::Client.new(environment: :production) + +# Other supported environments: +HiveAPI::Client.new(environment: :staging) +HiveAPI::Client.new(environment: :mock) +``` + +The client defaults to `:production`. It does not accept a custom base URL and it does not use global configuration. Connections use bounded connect and request timeouts, defaulting to 5 and 15 seconds respectively: + +```ruby +HiveAPI::Client.new( + environment: :staging, + open_timeout: 2, + timeout: 10 +) +``` + +Authentication and concrete Hive resources will be added in subsequent releases. + +### Response objects + +Response objects expose provider keys as snake-case Ruby methods, including nested hashes and arrays. The original provider payload remains available as a deeply frozen snapshot through `raw`, while `to_h` returns plain recursive hashes and arrays. + +```ruby +response = HiveAPI::Base.new( + "returnId" => "return-123", + "lineItems" => [{"merchantSKU" => "SKU-1"}] +) + +response.return_id # => "return-123" +response.line_items.first.merchant_sku # => "SKU-1" +response.raw.frozen? # => true +response.to_h # => {"return_id" => "return-123", ...} +``` + +## Development + +```sh +bundle install +bundle exec rake +gem build hive_api.gemspec +``` + +## License + +MIT License. See [LICENSE.txt](LICENSE.txt). diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..8ee8d21 --- /dev/null +++ b/Rakefile @@ -0,0 +1,10 @@ +# frozen_string_literal: true + +require "bundler/gem_tasks" +require "rspec/core/rake_task" +require "standard/rake" + +RSpec::Core::RakeTask.new(:spec) + +task default: %i[spec standard] +task release: %i[spec standard] diff --git a/hive_api.gemspec b/hive_api.gemspec new file mode 100644 index 0000000..4dbe710 --- /dev/null +++ b/hive_api.gemspec @@ -0,0 +1,32 @@ +# frozen_string_literal: true + +require_relative "lib/hive_api/version" + +Gem::Specification.new do |spec| + spec.name = "hive_api" + spec.version = HiveAPI::VERSION + spec.authors = ["PostCo"] + spec.email = ["engineering@postco.co"] + + spec.summary = "Rails-independent Ruby client for the Hive Merchant API" + spec.description = "A small Ruby client foundation for integrating with Hive without depending on Rails." + spec.homepage = "https://github.com/PostCo/hive_api" + spec.license = "MIT" + spec.required_ruby_version = ">= 3.3.0" + + spec.metadata["source_code_uri"] = spec.homepage + spec.metadata["changelog_uri"] = "#{spec.homepage}/blob/main/CHANGELOG.md" + spec.metadata["rubygems_mfa_required"] = "true" + + spec.files = Dir["lib/**/*", "CHANGELOG.md", "README.md", "LICENSE.txt"] + spec.require_paths = ["lib"] + + spec.add_dependency "faraday", "~> 2.0" + spec.add_dependency "faraday-net_http", ">= 2.0" + spec.add_dependency "activesupport", ">= 7.0" + + spec.add_development_dependency "rake" + spec.add_development_dependency "rspec", "~> 3.0" + spec.add_development_dependency "webmock", "~> 3.0" + spec.add_development_dependency "standard" +end diff --git a/lib/hive_api.rb b/lib/hive_api.rb new file mode 100644 index 0000000..4636a7a --- /dev/null +++ b/lib/hive_api.rb @@ -0,0 +1,14 @@ +# frozen_string_literal: true + +require_relative "hive_api/version" + +module HiveAPI + autoload :Client, "hive_api/client" + autoload :Base, "hive_api/object" + autoload :Resource, "hive_api/resource" + autoload :Error, "hive_api/errors" + autoload :APIError, "hive_api/errors" + + module Objects + end +end diff --git a/lib/hive_api/client.rb b/lib/hive_api/client.rb new file mode 100644 index 0000000..7b96338 --- /dev/null +++ b/lib/hive_api/client.rb @@ -0,0 +1,52 @@ +# frozen_string_literal: true + +require "faraday" + +module HiveAPI + class Client + PRODUCTION_BASE_URL = "https://app.hive.app/merchant_api/v2/" + STAGING_BASE_URL = "https://staging.app.hive.app/merchant_api/v2/" + MOCK_BASE_URL = "https://hive-merchant-api.redocly.app/_mock/merchant-api-v2/mapi_v2_oas31/" + BASE_URLS = { + production: PRODUCTION_BASE_URL, + staging: STAGING_BASE_URL, + mock: MOCK_BASE_URL + }.freeze + DEFAULT_ENVIRONMENT = :production + DEFAULT_OPEN_TIMEOUT = 5 + DEFAULT_TIMEOUT = 15 + + attr_reader :adapter, :base_url, :environment, :open_timeout, :timeout + + def initialize(environment: DEFAULT_ENVIRONMENT, adapter: Faraday.default_adapter, + open_timeout: DEFAULT_OPEN_TIMEOUT, timeout: DEFAULT_TIMEOUT) + @environment = normalize_environment(environment) + @base_url = BASE_URLS.fetch(@environment) + @adapter = adapter + @open_timeout = open_timeout + @timeout = timeout + end + + def connection + @connection ||= Faraday.new do |connection| + connection.url_prefix = base_url + connection.options.open_timeout = open_timeout + connection.options.timeout = timeout + connection.headers["Accept"] = "application/json" + connection.request :json + connection.response :json, content_type: /\bjson/ + connection.adapter adapter + end + end + + private + + def normalize_environment(environment) + normalized = environment.respond_to?(:to_sym) ? environment.to_sym : environment + return normalized if BASE_URLS.key?(normalized) + + raise ArgumentError, + "environment must be one of: #{BASE_URLS.keys.join(", ")}" + end + end +end diff --git a/lib/hive_api/errors.rb b/lib/hive_api/errors.rb new file mode 100644 index 0000000..4d372ff --- /dev/null +++ b/lib/hive_api/errors.rb @@ -0,0 +1,7 @@ +# frozen_string_literal: true + +module HiveAPI + class Error < StandardError; end + + class APIError < Error; end +end diff --git a/lib/hive_api/object.rb b/lib/hive_api/object.rb new file mode 100644 index 0000000..cda907c --- /dev/null +++ b/lib/hive_api/object.rb @@ -0,0 +1,71 @@ +# frozen_string_literal: true + +require "ostruct" +require "active_support/core_ext/string/inflections" + +module HiveAPI + class Base < OpenStruct + attr_reader :original_response + + def self.new(attributes) + return attributes.map { |item| super(item) } if attributes.is_a?(Array) + + super + end + + def initialize(attributes) + @original_response = deep_freeze(attributes) + super(to_ostruct(attributes)) + end + + def to_hash + ostruct_to_hash(self) + end + + alias_method :to_h, :to_hash + + def raw + @original_response + end + + private + + def to_ostruct(object) + case object + when Hash + OpenStruct.new( + object.transform_keys { |key| key.to_s.underscore } + .transform_values { |value| to_ostruct(value) } + ) + when Array + object.map { |value| to_ostruct(value) } + else + object + end + end + + def deep_freeze(object) + case object + when Hash then object.transform_values { |value| deep_freeze(value) }.freeze + when Array then object.map { |item| deep_freeze(item) }.freeze + else object.respond_to?(:freeze) ? object.freeze : object + end + end + + def ostruct_to_hash(object) + case object + when OpenStruct + object.each_pair.to_h + .transform_keys(&:to_s) + .transform_values { |value| ostruct_to_hash(value) } + when Array + object.map { |value| ostruct_to_hash(value) } + when Hash + object.transform_keys(&:to_s) + .transform_values { |value| ostruct_to_hash(value) } + else + object + end + end + end +end diff --git a/lib/hive_api/resource.rb b/lib/hive_api/resource.rb new file mode 100644 index 0000000..928f4ff --- /dev/null +++ b/lib/hive_api/resource.rb @@ -0,0 +1,35 @@ +# frozen_string_literal: true + +require "json" + +module HiveAPI + class Resource + attr_reader :client + + def initialize(client) + @client = client + end + + private + + def get_request(path, params: {}, headers: {}) + handle_response(client.connection.get(path, params, headers)) + end + + def post_request(path, body:, headers: {}) + handle_response(client.connection.post(path, body, headers)) + end + + def handle_response(response) + parse_body(response.body) + end + + def parse_body(body) + return body unless body.is_a?(String) + + JSON.parse(body) + rescue JSON::ParserError + body + end + end +end diff --git a/lib/hive_api/version.rb b/lib/hive_api/version.rb new file mode 100644 index 0000000..592c3b9 --- /dev/null +++ b/lib/hive_api/version.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true + +module HiveAPI + VERSION = "0.1.0" +end diff --git a/spec/gemspec_spec.rb b/spec/gemspec_spec.rb new file mode 100644 index 0000000..33ff8d1 --- /dev/null +++ b/spec/gemspec_spec.rb @@ -0,0 +1,29 @@ +# frozen_string_literal: true + +RSpec.describe "hive_api.gemspec" do + subject(:specification) do + Gem::Specification.load(File.expand_path("../hive_api.gemspec", __dir__)) + end + + it "requires compatible Ruby and the PostCo runtime dependencies" do + expect(specification.required_ruby_version).to be_satisfied_by(Gem::Version.new("3.3.0")) + expect(specification.runtime_dependencies.map(&:name).sort) + .to eq(%w[activesupport faraday faraday-net_http]) + end + + it "uses the PostCo development toolchain" do + expect(specification.development_dependencies.map(&:name).sort) + .to eq(%w[rake rspec standard webmock]) + end + + it "packages library files and project documentation" do + expect(specification.files).to include( + "lib/hive_api.rb", + "lib/hive_api/client.rb", + "README.md", + "LICENSE.txt", + "CHANGELOG.md" + ) + expect(specification.files).not_to include(a_string_starting_with("spec/")) + end +end diff --git a/spec/hive_api/client_spec.rb b/spec/hive_api/client_spec.rb new file mode 100644 index 0000000..095e6bf --- /dev/null +++ b/spec/hive_api/client_spec.rb @@ -0,0 +1,114 @@ +# frozen_string_literal: true + +require "json" + +RSpec.describe HiveAPI::Client do + describe "environment selection" do + { + production: described_class::PRODUCTION_BASE_URL, + staging: described_class::STAGING_BASE_URL, + mock: described_class::MOCK_BASE_URL + }.each do |environment, base_url| + it "uses the fixed #{environment} base URL" do + client = described_class.new(environment: environment) + + expect(client.environment).to eq(environment) + expect(client.base_url).to eq(base_url) + expect(client.connection.url_prefix.to_s).to eq(base_url) + end + end + + it "defaults to production" do + client = described_class.new + + expect(client.environment).to eq(:production) + expect(client.base_url).to eq(described_class::PRODUCTION_BASE_URL) + end + + it "accepts an environment name as a string" do + expect(described_class.new(environment: "staging").environment).to eq(:staging) + end + + it "rejects any environment outside the fixed set" do + expect { described_class.new(environment: "https://example.test") } + .to raise_error(ArgumentError, /production, staging, mock/) + end + + it "does not accept a caller-supplied base URL" do + expect { described_class.new(base_url: "https://example.test") } + .to raise_error(ArgumentError, /unknown keyword: :base_url/) + end + end + + describe "#connection" do + subject(:client) { described_class.new } + + it "builds the connection lazily" do + expect(client.instance_variable_defined?(:@connection)).to be(false) + + client.connection + + expect(client.instance_variable_defined?(:@connection)).to be(true) + end + + it "memoizes the connection" do + expect(client.connection).to be(client.connection) + end + + it "sets bounded default timeouts" do + expect(client.connection.options.open_timeout).to eq(described_class::DEFAULT_OPEN_TIMEOUT) + expect(client.connection.options.timeout).to eq(described_class::DEFAULT_TIMEOUT) + end + + it "accepts explicit timeout values" do + client = described_class.new(open_timeout: 1, timeout: 3) + + expect(client.connection.options.open_timeout).to eq(1) + expect(client.connection.options.timeout).to eq(3) + end + + it "uses JSON request middleware and parses JSON response content types" do + stub_request(:post, endpoint("echo")) + .with( + body: JSON.generate("returnId" => "return-123"), + headers: { + "Accept" => "application/json", + "Content-Type" => "application/json" + } + ) + .to_return( + status: 200, + body: JSON.generate("returnId" => "return-123"), + headers: {"Content-Type" => "application/json; charset=utf-8"} + ) + + response = client.connection.post("echo", returnId: "return-123") + + expect(response.body).to eq("returnId" => "return-123") + end + + it "does not parse JSON when the response content type is not JSON" do + body = JSON.generate("status" => "ok") + stub_request(:get, endpoint("plain")) + .to_return(status: 200, body: body, headers: {"Content-Type" => "text/plain"}) + + expect(client.connection.get("plain").body).to eq(body) + end + end + + describe "adapter injection" do + it "uses Faraday's default adapter by default" do + expect(described_class.new.adapter).to eq(Faraday.default_adapter) + end + + it "configures an injected adapter" do + client = described_class.new(adapter: :test) + + expect(client.connection.builder.adapter.klass).to eq(Faraday::Adapter::Test) + end + end + + def endpoint(path) + "#{described_class::PRODUCTION_BASE_URL}#{path}" + end +end diff --git a/spec/hive_api/object_spec.rb b/spec/hive_api/object_spec.rb new file mode 100644 index 0000000..bbbd58f --- /dev/null +++ b/spec/hive_api/object_spec.rb @@ -0,0 +1,80 @@ +# frozen_string_literal: true + +require "json" + +RSpec.describe HiveAPI::Base do + describe ".new" do + it "maps a top-level array into response objects" do + response = [{"returnId" => "one"}, {"returnId" => "two"}] + + result = described_class.new(response) + + expect(result.map(&:class)).to eq([described_class, described_class]) + expect(result.map(&:return_id)).to eq(%w[one two]) + end + end + + describe "response access" do + subject(:object) do + described_class.new( + "returnId" => "return-123", + "sendBackAddress" => {"postalCode" => "10115"}, + "lineItems" => [{"merchantSKU" => "SKU-1"}] + ) + end + + it "recursively exposes snake-case methods" do + expect(object.return_id).to eq("return-123") + expect(object.send_back_address.postal_code).to eq("10115") + expect(object.line_items.first.merchant_sku).to eq("SKU-1") + end + + it "retains a deeply frozen raw payload" do + expect(object.raw).to be(object.original_response) + expect(object.raw).to be_frozen + expect(object.raw.fetch("sendBackAddress")).to be_frozen + expect(object.raw.fetch("lineItems")).to be_frozen + expect(object.raw.fetch("lineItems").first).to be_frozen + expect(object.raw.fetch("returnId")).to be_frozen + end + end + + describe "hash conversion" do + let(:object) do + described_class.new( + "returnId" => "return-123", + "lineItems" => [{"merchantSKU" => "SKU-1"}] + ) + end + + let(:expected_hash) do + { + "return_id" => "return-123", + "line_items" => [{"merchant_sku" => "SKU-1"}] + } + end + + it "returns plain recursive structures from #to_h and #to_hash" do + expect(object.to_h).to eq(expected_hash) + expect(object.to_hash).to eq(expected_hash) + expect(contains_ostruct?(object.to_h)).to be(false) + end + + it "does not serialize OpenStruct table wrappers" do + expect(JSON.generate(object.to_h)).not_to include('"table"') + end + end + + def contains_ostruct?(value) + case value + when OpenStruct + true + when Hash + value.any? { |key, entry| contains_ostruct?(key) || contains_ostruct?(entry) } + when Array + value.any? { |entry| contains_ostruct?(entry) } + else + false + end + end +end diff --git a/spec/hive_api/resource_spec.rb b/spec/hive_api/resource_spec.rb new file mode 100644 index 0000000..99d6c05 --- /dev/null +++ b/spec/hive_api/resource_spec.rb @@ -0,0 +1,75 @@ +# frozen_string_literal: true + +require "json" + +RSpec.describe HiveAPI::Resource do + let(:resource_class) do + Class.new(described_class) do + def fetch(path, params: {}, headers: {}) + get_request(path, params: params, headers: headers) + end + + def create(path, body:, headers: {}) + post_request(path, body: body, headers: headers) + end + end + end + + subject(:resource) { resource_class.new(client) } + + let(:client) { HiveAPI::Client.new(environment: :staging) } + + it "retains its client" do + expect(resource.client).to be(client) + end + + it "returns JSON parsed by Faraday for a JSON content type" do + stub_request(:get, endpoint("returns/return-123")) + .to_return( + status: 200, + body: JSON.generate("returnId" => "return-123"), + headers: {"Content-Type" => "application/json"} + ) + + expect(resource.fetch("returns/return-123")).to eq("returnId" => "return-123") + end + + it "falls back to parsing JSON served with an incorrect content type" do + stub_request(:get, endpoint("returns")) + .to_return( + status: 200, + body: JSON.generate("returns" => []), + headers: {"Content-Type" => "text/plain"} + ) + + expect(resource.fetch("returns")).to eq("returns" => []) + end + + it "preserves a non-JSON response body" do + stub_request(:get, endpoint("health")) + .to_return(status: 200, body: "healthy", headers: {"Content-Type" => "text/plain"}) + + expect(resource.fetch("health")).to eq("healthy") + end + + it "sends JSON POST bodies and caller headers through the connection" do + payload = {"returnId" => "return-123"} + stub_request(:post, endpoint("returns")) + .with( + body: JSON.generate(payload), + headers: { + "Content-Type" => "application/json", + "X-Request-ID" => "request-123" + } + ) + .to_return(status: 201, body: JSON.generate("created" => true)) + + expect( + resource.create("returns", body: payload, headers: {"X-Request-ID" => "request-123"}) + ).to eq("created" => true) + end + + def endpoint(path) + "#{HiveAPI::Client::STAGING_BASE_URL}#{path}" + end +end diff --git a/spec/hive_api_spec.rb b/spec/hive_api_spec.rb new file mode 100644 index 0000000..38f6368 --- /dev/null +++ b/spec/hive_api_spec.rb @@ -0,0 +1,49 @@ +# frozen_string_literal: true + +require "open3" +require "rbconfig" + +RSpec.describe HiveAPI do + it "has the scaffold version" do + expect(described_class::VERSION).to eq("0.1.0") + end + + it "autoloads the public foundation" do + expect(described_class::Client).to be_a(Class) + expect(described_class::Base).to be < OpenStruct + expect(described_class::Resource).to be_a(Class) + expect(described_class::Error).to be < StandardError + expect(described_class::APIError).to be < described_class::Error + expect(described_class::Objects).to be_a(Module) + expect(described_class::Objects.constants).to be_empty + end + + it "does not expose global configuration" do + expect(described_class).not_to respond_to(:configure) + expect(described_class).not_to respond_to(:configuration) + expect(described_class.const_defined?(:Configuration, false)).to be(false) + end + + it "loads in a clean Ruby process without Rails or Zeitwerk" do + script = <<~RUBY + require "hive_api" + HiveAPI::Client + HiveAPI::Base + HiveAPI::Resource + HiveAPI::Error + HiveAPI::APIError + abort "Rails loaded" if defined?(Rails) + abort "Zeitwerk loaded" if defined?(Zeitwerk) + RUBY + + _stdout, stderr, status = Open3.capture3( + {"BUNDLE_GEMFILE" => nil, "RUBYOPT" => nil}, + RbConfig.ruby, + "-I#{File.expand_path("../lib", __dir__)}", + "-e", + script + ) + + expect(status).to be_success, stderr + end +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 0000000..def0727 --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,22 @@ +# frozen_string_literal: true + +$LOAD_PATH.unshift File.expand_path("../lib", __dir__) + +require "hive_api" +require "webmock/rspec" + +WebMock.disable_net_connect! + +RSpec.configure do |config| + config.expect_with :rspec do |expectations| + expectations.include_chain_clauses_in_custom_matcher_descriptions = true + end + + config.mock_with :rspec do |mocks| + mocks.verify_partial_doubles = true + end + + config.shared_context_metadata_behavior = :apply_to_host_groups + config.order = :random + Kernel.srand config.seed +end From 88ae28686850472a4a89785250c8ac08735c7c77 Mon Sep 17 00:00:00 2001 From: hanswys Date: Tue, 15 Sep 2026 14:55:56 +0800 Subject: [PATCH 2/2] Default Hive client to staging sandbox --- CHANGELOG.md | 2 +- README.md | 13 ++++++------- lib/hive_api/client.rb | 28 ++++++++-------------------- spec/hive_api/client_spec.rb | 34 +++++++++++----------------------- spec/hive_api/resource_spec.rb | 4 ++-- 5 files changed, 28 insertions(+), 53 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 36c6a9a..4d6ca89 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,6 @@ ### Added -- Rails-independent Hive API client foundation with fixed production, staging, and official mock environments. +- Rails-independent Hive API client foundation with fixed production and staging environments, defaulting safely to staging. - Bounded Faraday connections with injectable adapters and safe JSON middleware. - Shared resource and response-object foundations. diff --git a/README.md b/README.md index 4444290..5f5a861 100644 --- a/README.md +++ b/README.md @@ -14,23 +14,22 @@ Then run `bundle install`. ## Usage -Require the gem and select one of Hive's fixed API environments when building a client: +Require the gem and build a client. It defaults to Hive's staging API: ```ruby require "hive_api" -client = HiveAPI::Client.new(environment: :production) +client = HiveAPI::Client.new -# Other supported environments: -HiveAPI::Client.new(environment: :staging) -HiveAPI::Client.new(environment: :mock) +# Use the production API explicitly: +HiveAPI::Client.new(sandbox: false) ``` -The client defaults to `:production`. It does not accept a custom base URL and it does not use global configuration. Connections use bounded connect and request timeouts, defaulting to 5 and 15 seconds respectively: +The client does not accept a custom base URL and it does not use global configuration. Connections use bounded connect and request timeouts, defaulting to 5 and 15 seconds respectively: ```ruby HiveAPI::Client.new( - environment: :staging, + sandbox: true, open_timeout: 2, timeout: 10 ) diff --git a/lib/hive_api/client.rb b/lib/hive_api/client.rb index 7b96338..8ae9cd9 100644 --- a/lib/hive_api/client.rb +++ b/lib/hive_api/client.rb @@ -4,24 +4,16 @@ module HiveAPI class Client - PRODUCTION_BASE_URL = "https://app.hive.app/merchant_api/v2/" - STAGING_BASE_URL = "https://staging.app.hive.app/merchant_api/v2/" - MOCK_BASE_URL = "https://hive-merchant-api.redocly.app/_mock/merchant-api-v2/mapi_v2_oas31/" - BASE_URLS = { - production: PRODUCTION_BASE_URL, - staging: STAGING_BASE_URL, - mock: MOCK_BASE_URL - }.freeze - DEFAULT_ENVIRONMENT = :production + LIVE_BASE_URL = "https://app.hive.app/merchant_api/v2/" + TEST_BASE_URL = "https://staging.app.hive.app/merchant_api/v2/" DEFAULT_OPEN_TIMEOUT = 5 DEFAULT_TIMEOUT = 15 - attr_reader :adapter, :base_url, :environment, :open_timeout, :timeout + attr_reader :adapter, :open_timeout, :timeout - def initialize(environment: DEFAULT_ENVIRONMENT, adapter: Faraday.default_adapter, + def initialize(sandbox: true, adapter: Faraday.default_adapter, open_timeout: DEFAULT_OPEN_TIMEOUT, timeout: DEFAULT_TIMEOUT) - @environment = normalize_environment(environment) - @base_url = BASE_URLS.fetch(@environment) + @sandbox = sandbox @adapter = adapter @open_timeout = open_timeout @timeout = timeout @@ -29,7 +21,7 @@ def initialize(environment: DEFAULT_ENVIRONMENT, adapter: Faraday.default_adapte def connection @connection ||= Faraday.new do |connection| - connection.url_prefix = base_url + connection.url_prefix = sandbox? ? TEST_BASE_URL : LIVE_BASE_URL connection.options.open_timeout = open_timeout connection.options.timeout = timeout connection.headers["Accept"] = "application/json" @@ -41,12 +33,8 @@ def connection private - def normalize_environment(environment) - normalized = environment.respond_to?(:to_sym) ? environment.to_sym : environment - return normalized if BASE_URLS.key?(normalized) - - raise ArgumentError, - "environment must be one of: #{BASE_URLS.keys.join(", ")}" + def sandbox? + @sandbox end end end diff --git a/spec/hive_api/client_spec.rb b/spec/hive_api/client_spec.rb index 095e6bf..c463d10 100644 --- a/spec/hive_api/client_spec.rb +++ b/spec/hive_api/client_spec.rb @@ -4,34 +4,22 @@ RSpec.describe HiveAPI::Client do describe "environment selection" do - { - production: described_class::PRODUCTION_BASE_URL, - staging: described_class::STAGING_BASE_URL, - mock: described_class::MOCK_BASE_URL - }.each do |environment, base_url| - it "uses the fixed #{environment} base URL" do - client = described_class.new(environment: environment) - - expect(client.environment).to eq(environment) - expect(client.base_url).to eq(base_url) - expect(client.connection.url_prefix.to_s).to eq(base_url) - end - end - - it "defaults to production" do + it "defaults to the staging API" do client = described_class.new - expect(client.environment).to eq(:production) - expect(client.base_url).to eq(described_class::PRODUCTION_BASE_URL) + expect(client.connection.url_prefix.to_s).to eq(described_class::TEST_BASE_URL) end - it "accepts an environment name as a string" do - expect(described_class.new(environment: "staging").environment).to eq(:staging) + it "uses the staging API in sandbox mode" do + client = described_class.new(sandbox: true) + + expect(client.connection.url_prefix.to_s).to eq(described_class::TEST_BASE_URL) end - it "rejects any environment outside the fixed set" do - expect { described_class.new(environment: "https://example.test") } - .to raise_error(ArgumentError, /production, staging, mock/) + it "uses the production API outside sandbox mode" do + client = described_class.new(sandbox: false) + + expect(client.connection.url_prefix.to_s).to eq(described_class::LIVE_BASE_URL) end it "does not accept a caller-supplied base URL" do @@ -109,6 +97,6 @@ end def endpoint(path) - "#{described_class::PRODUCTION_BASE_URL}#{path}" + "#{described_class::TEST_BASE_URL}#{path}" end end diff --git a/spec/hive_api/resource_spec.rb b/spec/hive_api/resource_spec.rb index 99d6c05..caa750a 100644 --- a/spec/hive_api/resource_spec.rb +++ b/spec/hive_api/resource_spec.rb @@ -17,7 +17,7 @@ def create(path, body:, headers: {}) subject(:resource) { resource_class.new(client) } - let(:client) { HiveAPI::Client.new(environment: :staging) } + let(:client) { HiveAPI::Client.new } it "retains its client" do expect(resource.client).to be(client) @@ -70,6 +70,6 @@ def create(path, body:, headers: {}) end def endpoint(path) - "#{HiveAPI::Client::STAGING_BASE_URL}#{path}" + "#{HiveAPI::Client::TEST_BASE_URL}#{path}" end end