使用active_model_serializers实现API版本控制的正确方法 [英] Correct way to implement API versioning with active_model_serializers

查看:88
本文介绍了使用active_model_serializers实现API版本控制的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道已经存在一些问题,并且这是有关AMS无法处理的公开问题命名空间太有效(此版本控制方法使用了该命名空间),但我想确保自己在当前约束范围内处于正确的轨道.

I know there are already some questions and also this is a open issue regarding AMS not handling namespaces too efficiently (which is used by this versioning approach) but I wanted to be sure I am in the right track within the current constraints.

现在我正在使用Rails 5和AMS 0.10.1,所以我做了以下事情:

Right now I am using Rails 5 and AMS 0.10.1, so I did the following:

# config/initializers/active_model_serializer.rb
ActiveModelSerializers.config.serializer_lookup_enabled = false

禁用默认的序列化程序查找(无论如何都无法工作);和

to disable default serializer lookup (which didn't work anyway); and

# app/controllers/application_controller.rb
class ApplicationController < ActionController::API
  def get_serializer(resource, options = {})
    unless options[:each_serializer] || options[:serializer] then
      serializer = (self.class.name.gsub("Controller","").singularize + "Serializer").constantize
      resource.respond_to?(:to_ary) ? options[:each_serializer] = serializer : options[:serializer] = serializer
    end
    super(resource, options)
  end
end

覆盖默认情况下如何查找序列化器;我的控制器和序列化器是这样的:

to override how serializers are found by default; my controllers and serializer are like this:

# app/controllers/api/v2/api_controller.rb
module Api::V2
  class ApiController < ApplicationController
    ...

# app/controllers/api/v2/users_controller.rb
module Api::V2
  class UsersController < ApiController
    ...

# app/serializers/api/v2/user_serializer.rb
module Api::V2
  class UserSerializer < ActiveModel::Serializer
    ...    

现在,诸如ActiveModel::Serializer.serializer_for(object)之类的东西将无法正常工作,因此我还必须在每次测试之前使用example.metadata[:api_version]设置我的API请求版本来猴子修补我的请求规范,如果示例未设置,则会引发错误.

Now, things like ActiveModel::Serializer.serializer_for(object) won't work, so I had to also monkey patch my request specs using example.metadata[:api_version] to set the API version before each test and raising and error if the example didn't set it.

所以:

  1. 有没有更好的记录方法?
  2. 这几乎是正确的吗?
  3. 这种方法是否会进一步遇到问题?
  4. 如何改进?

推荐答案

由于我没有找到更好的方法,也没有记录在案,也没有任何地方,所以这似乎也是正确的,使用一段时间后我也没有遇到任何问题,这似乎是API版本控制的好方法.

Since I haven't found a better way, neither documented nor anywhere, it also seems to be correct and I haven't faced problems after a while using it, this appear to be a good approach for API versioning.

无论如何,我建议您谨慎使用此方法,以免更改您的API的较早支持版本的行为.仔细测试并通知您的客户有关旧版本的弃用和支持删除.

Anyway, I advise caution using this approach to not change behaviour of older supported versions for your API. Test carefully and notify your clients for deprecations and support removal for old versions.

这篇关于使用active_model_serializers实现API版本控制的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆