diff --git a/lib/scalingo/regional/addons.rb b/lib/scalingo/regional/addons.rb index 8a3d6c5..3b9ee5b 100644 --- a/lib/scalingo/regional/addons.rb +++ b/lib/scalingo/regional/addons.rb @@ -12,18 +12,16 @@ class Regional::Addons < API::Endpoint get :categories, "addon_categories", connected: false get :providers, "addon_providers", connected: false - def authenticate!(**params, &block) - response = token(**params, &block) - return response unless response.status == 200 + def database_client_for(app_id:, id:) + response = token(app_id: app_id, id: id) - client.token_holder.authenticate_database_with_bearer_token( - params[:id], - response.body[:token], - expires_at: Time.now + 1.hour, - raise_on_expired_token: client.config.raise_on_expired_token - ) + return nil unless response.status == 200 - response + db_url = Scalingo::Client::URLS.fetch(:database).fetch(client.region) + + db_client = Scalingo::Database.new(db_url, region: client.region) + db_client.token = response.body.fetch(:token) + db_client end end end diff --git a/spec/scalingo/regional/addons_spec.rb b/spec/scalingo/regional/addons_spec.rb index b78ad36..3f329c4 100644 --- a/spec/scalingo/regional/addons_spec.rb +++ b/spec/scalingo/regional/addons_spec.rb @@ -81,6 +81,38 @@ include_examples "requires some params", :app_id, :id it { is_expected.to have_requested(:post, api_path.merge("/apps/my-app-id/addons/addon-id/token")) } + + describe "database_client_for" do + subject(:db_client) { instance.database_client_for(**params) } + + before do + allow(Scalingo::Client::URLS).to receive(:fetch).with(:database).and_return({some_region: "http://localhost"}) + end + + context "with a valid response" do + before do + stub_request(:post, "http://localhost/apps/my-app-id/addons/addon-id/token").to_return( + body: {addon: {id: "addon-id", token: "some-token"}}.to_json, + status: 200, + headers: {content_type: "application/json"} + ) + end + + it "returns a database client" do + expect(subject).to be_a(Scalingo::Database) + expect(subject).to be_authenticated + expect(subject.token.value).to eq "some-token" + end + end + + context "with invalid params" do + before do + stub_request(:post, "http://localhost/apps/my-app-id/addons/addon-id/token").to_return(status: 404) + end + + it { is_expected.to be_nil } + end + end end describe "delete" do