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

查看:23
本文介绍了使用 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天全站免登陆