Skip to content

Instantly share code, notes, and snippets.

@rchasman
Created June 18, 2018 19:31
Show Gist options
  • Save rchasman/ef2894e326d54ae3cc25061c24d4758b to your computer and use it in GitHub Desktop.
Save rchasman/ef2894e326d54ae3cc25061c24d4758b to your computer and use it in GitHub Desktop.
class IntegrationService
def initialize(integration)
@integration = integration
end
def token_expired?
Time.current > @integration.expires_at
end
def refresh_token!
tokens = oauth_klass.refresh_token(@integration.refresh_token)
@integration.update_attributes(tokens)
end
def deauthorize!
oauth_klass.deauthorize(@integration.access_token)
@integration.destroy!
end
def get_as_json(endpoint, params = {})
JSON.parse(get_raw(endpoint, params).body)
end
def post_as_json(endpoint, payload)
JSON.parse(post_raw(endpoint, payload).body)
end
def patch_as_json(endpoint, payload)
JSON.parse(patch_raw(endpoint, payload).body)
end
def get_raw(endpoint, params = {})
@integration.refresh_token! if token_expired?
oauth_klass.authed_get(@integration.access_token, endpoint, params)
end
def post_raw(endpoint, payload)
@integration.refresh_token! if token_expired?
oauth_klass.authed_post(@integration.access_token, endpoint, payload)
end
def patch_raw(endpoint, payload)
@integration.refresh_token! if token_expired?
oauth_klass.authed_patch(@integration.access_token, endpoint, payload)
end
protected
def oauth_klass; end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment