Skip to content

Commit

Permalink
feat(db api): spawn a db api client for a given addon id
Browse files Browse the repository at this point in the history
  • Loading branch information
ksol committed Apr 12, 2024
1 parent 00488c0 commit c4b628d
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 10 deletions.
18 changes: 8 additions & 10 deletions lib/scalingo/regional/addons.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
32 changes: 32 additions & 0 deletions spec/scalingo/regional/addons_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit c4b628d

Please sign in to comment.