刮一整个 API 还是严重依赖它?

Scrape an entire API or rely heavily on it?

我正在 rails 建立一个度假村评论网站。目前,一个User有很多评论,每个Review属于一个User

评论 table 包含一个 expedia_id 字段。所有数据——酒店名称、图像、描述等都是从 Expedia API 动态提取的,使用针对此 ID 的查找。例如,当在控制器中点击 show 操作时,它会使用 expedia_id 向 Expedia and 我的数据库发出请求以获取所有评论和内容,并在一页上呈现所有内容。还将请求填充主页(我正在考虑 Featured table 和 expedia_id 列)

由于我的整个网站严重依赖 API 而我没有 Resort table,再加上考虑到大量用户,很多 请求将被发送到 Expedia API,将结果抓取并写入我的数据库是否有意义,创建记录供以后使用?

中间立场将是最好的解决方案。 创建一个 table 和模型来本地存储活跃的度假村。在一段时间后使您的本地副本过期(由 Expedia 上的度假村更改频率决定)并且仅在新的系统度假村上 ping api,或加载已过期的度假村

这将是如何完成此操作的一个基本示例

class Resort < ApplicationRecord #for Rails <=4 do ActiveRecord::Base
  after_find :maybe_update_from_expedia
  ExpirationTime = 1.day #change to fit what is needed

  def self.find_by_expedia_id(expedia_id)
    result = self.where(expedia_id: expedia_id).first
    result || self.create_by_expedia_id(expedia_id)
  end

  def maybe_update_from_expedia
    update_from_expedia if expire_at.nil? || expire_at < Time.now
  end

  private
  def self.create_by_expedia_id(expedia_id)
    record = new(expedia_id: expedia_id)
    record.maybe_update_from_expedia
    record
  end

  def update_from_expedia
    #fetch record from expedia
    #update local data
    self.expire_time = Time.now + ExpirationTime
    self.save
  end
end

根据 engineersmnky 的建议,这可以浓缩为

class Resort < ApplicationRecord #for Rails <=4 do ActiveRecord::Base
  after_initialize :maybe_update_from_expedia
  ExpirationTime = 1.day #change to fit what is needed

  private

  def maybe_update_from_expedia
    update_from_expedia if expire_at.nil? || expire_at < Time.now
  end

  def update_from_expedia
    #fetch record from expedia
    #update local data
    self.expire_time = Time.now + ExpirationTime
    self.save
  end
end

如果所有获取请求都使用 Resort.find_or_create_by(expedia_id: expedia_id)