Sha256: 4cd8f70f87905adf497a0fc14d8bbaa6b66cc8eb2919680e2975b8424f301933

Contents?: true

Size: 1.42 KB

Versions: 1

Compression:

Stored size: 1.42 KB

Contents

require 'wework/token/store'
require 'wework/token/redis_store'

module Wework
  module Api
    class Base
      attr_reader :corp_id, :agent_id, :agent_secret
      attr_accessor :options

      delegate :access_token, to: :token_store

      def initialize(corp_id, agent_id, agent_secret, options={})
        @corp_id      = corp_id
        @agent_id     = agent_id
        @agent_secret = agent_secret
        @options      = options
      end

      def token_store
        @token_store ||= Token::RedisStore.new self
      end

      def request
        @request ||= Wework::Request.new(API_ENDPOINT, false)
      end

      def get(path, headers = {})
        with_access_token(headers[:params]) do |params|
          request.get path, headers.merge(params: params)
        end
      end

      def post(path, payload, headers = {})
        with_access_token(headers[:params]) do |params|
          request.post path, payload, headers.merge(params: params)
        end
      end

      def post_file(path, file, headers = {})
        with_access_token(headers[:params]) do |params|
          request.post_file path, file, headers.merge(params: params)
        end
      end

      def with_access_token(params = {}, tries = 2)
        params ||= {}
        yield(params.merge(access_token: access_token))
      rescue AccessTokenExpiredError
        token_store.refresh_token
        retry unless (tries -= 1).zero?
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
wework-0.1.2 lib/wework/api/base.rb