使用 batch_save 时 Xeroizer RateLimitExceeded

Xeroizer RateLimitExceeded when using batch_save

我正在使用 Xero API 检索本月的所有发票,然后检索所有 CreditNotes,然后我计划适当分配学分。

在此之前,我需要授权我所有的发票和信用票据。当我到达保存更新的位置时,我遇到了 Xeroizer::OAuth::RateLimitExceeded 异常,被验证步骤抛出,该验证步骤似乎是通过 #download_complete_record 单独检索每条记录! lib/xeroizer/record/record_association_helper.rb:131.

我尝试在保存之前手动设置所有对象的 complete_record_downloaded 标志,但随后我收到验证错误,说发票没有行项目,这是预期的。

这就是我想要做的,是否有其他方法可以解决这个问题,这样它就不会在发送更新之前尝试重新验证所有记录?

require 'xeroizer'
key = Rails.application.secrets.xero[:key]
secret = Rails.application.secrets.xero[:secret]
cert = Rails.application.secrets.xero[:cert]
xeroizer = Xeroizer::PrivateApplication.new(key, secret, cert)

issue_date = Date.new(2019,11,22)
# Retrieving this broad selection of invoices here as it's used later in this worker for other purposes
xero_all_invoices = xeroizer.Invoice.all(where: "AmountDue>0")

xero_invoices = xero_all_invoices.select{|i| i.date == issue_date && i.status == 'DRAFT'}
xeroizer.Invoice.batch_save do
  xero_invoices.each{|i| i.status = 'AUTHORISED' }
end

# At this point, the Xeroizer::OAuth::RateLimitExceeded exception is thrown.

异常回溯的相关部分如下:

.../xeroizer/http.rb:175:in `handle_oauth_error!'
.../xeroizer/http.rb:124:in `http_request'
.../xeroizer/http.rb:31:in `http_get'
.../xeroizer/record/base_model.rb:152:in `find'
.../xeroizer/record/base.rb:100:in `download_complete_record!'
.../xeroizer/record/record_association_helper.rb:131:in `block in define_association_attribute'
.../xeroizer/record/base.rb:54:in `[]'
.../xeroizer/record/validators/associated_validator.rb:12:in `valid?'
.../xeroizer/record/validators/validator.rb:15:in `validate'
.../xeroizer/record/validation_helper.rb:59:in `block in valid?'
.../xeroizer/record/validation_helper.rb:58:in `each'
.../xeroizer/record/validation_helper.rb:58:in `valid?'
.../xeroizer/record/base_model.rb:161:in `each'
.../xeroizer/record/base_model.rb:161:in `all?'
.../xeroizer/record/base_model.rb:161:in `save_records'

作为参考,我已经在 Xeroizer gem 问题页面上询问 same question,但没有得到回复,所以现在在这里询问。

我已经找到了解决方案,下面是新的工作代码片段以供参考。

这可能有点老套,因为它在对象上设置了 complete_record_downloaded 标志,该标志与对象的状态不完全匹配,因此我不知道的其他方法可能会有副作用,但就我的目的而言,这似乎按预期工作。

find_in_batches 方法检索行项目以及其他必要的发票属性以成功更新它们,从而解决了我遇到的问题。

再次阅读 Xero API 文档后,我发现发送更新到发票需要至少列出所有行项目 ID,否则它们将在更新期间被删除,这解释了为什么要执行此步骤有必要。

issue_date = Date.new(2019,11,22)
# Retrieving this broad selection of invoices here as it's used later in this worker for other purposes
xero_all_invoices = []
xeroizer.Invoice.find_in_batches(where: "AmountDue>0") do |batch|
  batch.each do |invoice|
    invoice.complete_record_downloaded = true
    xero_all_invoices << invoice
  end
end

xero_invoices = xero_all_invoices.select{|i| i.date == issue_date && i.status == 'DRAFT'}
xeroizer.Invoice.batch_save do
  xero_invoices.each{|i| i.status = 'AUTHORISED' }
end
# Save successful