ruby Rails 7 -使用多个API响应

yyyllmsg  于 2023-04-29  发布在  Ruby
关注(0)|答案(1)|浏览(96)

在我的Rails 7应用程序中,我已经与第三方API集成。响应可能包含response['next_page'],这意味着响应是分页的。我想在响应中存在next_page键时消耗所有页面。下面我的客户:

module Customers
  module Settlements
    class Client
      def self.with_account(account) = new(account.id)

      def initialize(account_id)
        @conn = setup_conn(Rails.application.config.settlements_url, account_id)
      end

      def fetch_report(page:, limit: 500)
        handle_response(@conn.get("reports?page=#{page}&limit=#{limit}"))
      end
     
     # (...) other private methods
    end
  end
end

有没有什么常用的方法可以使用所有页面?

s1ag04yj

s1ag04yj1#

您可以while有下一页,或loop和休息,或:

def get page:
  mock_api = {
    1 => {next_page: 2, data: "stuff1"},
    2 => {next_page: 3, data: "stuff2"},
    3 => {data: "stuffLast"}
  }
  mock_api[page]
end

def fetch_all page: 1, &b
   return unless page                         # finish when no more pages

   response = get(page:)                      # get things
   yield response[:data]                      # process things
   fetch_all page: response[:next_page], &b   # get more things
end
>> fetch_all { |data| p data }
"stuff1"
"stuff2"
"stuffLast"
=> nil

相关问题