I made integration with Strava, now it’s time to get activities from them. I want to get all of them because I need history for my bikes. Otherwise, I would probably be interested in only new ones.
For this case I’m going to create new endpoint - get_activities
. This endpoint is going to do three things.
def get_activities(request)
update_tokens
activities = fetch_all_activities
[200, {"content-type" => "application/json"}, [activities.to_json]]
end
First thing - update tokens. Tokens have a short lifetime so it’s nice to update them every time we are calling external API. Otherwise, users will have to authorize in Strava again.
def update_tokens
response = @strava_oauth_client.oauth_token(
refresh_token: StravaIntegration::Repository.new.get_refresh_token,
grant_type: "refresh_token"
)
StravaIntegration::Repository.new.update_credentials(
access_token: response.access_token, refresh_token: response.refresh_token
)
end
Second thing is fetching all activities.
def fetch_all_activities
client = Strava::Api::Client.new(access_token: StravaIntegration::Repository.new.get_access_token)
page = 1
all_activities = []
loop do
activities = client.athlete_activities(page: page)
activities.each { |activity| all_activities << activity.to_h }
break if activities.empty?
page += 1
end
all_activities
end
The fourth thing is the return response, with all activities
[200, {"content-type" => "application/json"}, [activities.to_json]]
As you can see, there is nothing related to saving in database. It’s because I don’t have my own activities module yet. I’m going to do this in the next step, with my own rules, I want to convert Strava to something universal with the information that I need. But right now, getting activities from external API works fine. As always you can check my code on github