Ruby on Rails API 命名空间作为默认路径

Ruby on Rails API namespace as default path

我正在按照本教程设置我的 Rails API 服务器:building-awesome-rails-apis-part-1

一切正常,除了提到不必在路由中指示名称空间的部分。例如

Now our URls look like: http://api.example.com/v1/people or just http://api.example.com/people if you don’t use the version, it doesn’t interfere with your regular people routes, and it looks great.

当我调用 http://api.mydomain.com/v1/therapists/ 时它可以工作,但是当我尝试在 URL 中省略 v1 命名空间时它不起作用,我需要做任何额外的配置吗?

我正在使用 Rails 6.0.3.4

这是我的特定 routes.rb 文件:

Rails.application.routes.draw do
  namespace :api, :path => "", :constraints => {:subdomain => "api"} do
    namespace :v1 do
      resources :therapists do
        resources :appointments
      end
    end
  end
end

解决方案

按照 zhisme 的建议,我使用了 rack-rewrite gem 来做我想做的事情。

首先,我将 gem 添加到我的 Gemfile 中:

gem 'rack-rewrite', '~> 1.5', '>= 1.5.1'

之后我在config/application.rb文件中添加了配置

  config.middleware.insert_before(Rack::Runtime, Rack::Rewrite) do
    rewrite '/therapists', '/v1/therapists'
  end

它奏效了。

如果您在 URL 中省略了 v1 命名空间,您还必须将其从 routes.rb 文件中删除。

教程中的引述指出“如果您不使用该版本,则仅 http://api.example.com/people”,意思是如果您不在 routes.rb 中包含 v1 命名空间文件。

为了实现这一点,您需要在 Rack 代码中插入。有一个 gem rack-rewrite 可以在 Rails 代码执行之前进行重定向,因此在 rails 路由解析之前。检查他们的自述文件以进行安装。

所以根据你的问题修改 README 示例,你可以做类似的事情

config.middleware.insert_before(Rack::Runtime, Rack::Rewrite) do
  rewrite '/api/therapists/appointments', '/api/v1/therapists/appointments'
end

或者您可以进行重定向,让您的 api 消费者知道正确的 url 有点不同

config.middleware.insert_before(Rack::Runtime, Rack::Rewrite) do
  moved_permanently '/api/therapists/appointments', '/api/v1/therapists/appointments'
end

有很好的article描述了不同的解决方案,请查看更多详细信息。