我应该如何从 HALT 不可用的类内部返回 Sinatra HTTP 错误



我有一个大型后端API,用于我的原生应用程序,该API内置于Sinatra中,该API也为一些管理网页提供服务。我正在尝试干涸代码库并将代码重构为 lib 目录中的类。

我的 API 客户端需要状态和消息,例如 200 OK 或 404 找不到配置文件。我通常会用类似 halt 404, 'Profile Not Found' 的东西来做这件事.

使用类内部的 HTTP 状态代码和消息halt的最简单方法是什么?


旧湿代码

post '/api/process_something'
  halt 403, 'missing profile_id' unless params[:profile_id].present?
  halt 404, 'offer not found' unless params[:offer_id].present?
  do_some_processing
  200
end

新的干代码

post '/api/process_something'
  offer_manager = OfferManager.new
  offer_manager.process_offer(params: params)
end

offer_manager.rb

class OfferManager
  def process_offer(params:)
    # halt 403, 'missing profile_id' unless params[:profile_id].present?
    # halt 404, 'offer not found' unless params[:offer_id].present?
    # halt doesn't work from in here
    do_some_processing
    200
  end
end 

这个问题对于 CodeReview 来说可能更好,但您可以在这里的 OO 设计中看到一种方法是"停止"路径和"快乐"路径。 你的类只需要实现一些方法来帮助它在你的所有sinatra路由和方法中保持一致。

这是一种方法,使用继承在其他类中采用这种接口很容易。

post '/api/process_something' do
  offer_manager = OfferManager.new(params)
  # error guard clause
  halt offer_manager.status, offer_manager.halt_message if offer_manager.halt?
  # validations met, continue to process
  offer_manager.process_offer
  # return back 200
  offer_manager.status
end

class OfferManager
  attr_reader :status, :params, :halt_message
  def initialize(params)
    @params = params
    validate_params
  end
  def process_offer
    do_some_processing
  end
  def halt?
    # right now we just know missing params is one error to halt on but this is where
    # you could implement more business logic if need be
    missing_params?
  end
  private
  def validate_params
    if missing_params?
      @status = 404
      @halt_message = "missing #{missing_keys.join(", ")} key(s)"
    else
      @status = 200
    end
  end
  def do_some_processing
    # go do other processing
  end
  def missing_params?
    missing_keys.size > 0
  end
  def missing_keys
    expected_keys = [:profile_id, :offer_id]
    params.select { |k, _| !expected_keys.has_key?(k) }
  end
end

最新更新