【问题标题】:How to include token and other session information to send to front end?如何包含令牌和其他会话信息以发送到前端?
【发布时间】:2016-04-29 05:02:34
【问题描述】:

我在 API 控制器中有以下方法:

module Api
  module V1
    class ArticlesController < Api::BaseController

      def show
        article = Article.find(params[:id])
        render json: article
      end

end end end

在使用 active_model_serializers gem 时,我有以下序列化程序:

class Api::V1::ArticleSerializer < ActiveModel::Serializer
  attributes :id, :author_id, :title, :description
end

对于所有 API 请求,服务器应包含有关会话的信息,例如 api 令牌和当前用户。因此,在上述情况下,生成的 json 不仅应包含文章序列化程序中提到的属性,还应包含例如 api 令牌。

通常在何处以及如何包含此会话信息以发送到 API 前端?除了在这种情况下文章序列化程序之外,这可能是在一个单独的序列化程序中吗?

【问题讨论】:

    标签: ruby-on-rails ruby json api serialization


    【解决方案1】:

    由于您希望将此信息附加到所有 API 响应,因此有一个负责此的超类序列化程序是有意义的,所有其他序列化程序都继承自:

    class SerializerWithSessionMetadata < ActiveModel::Serializer
      attributes :token, :user
    
      def token
        # ...
      end
    
      def user
        # ...
      end
    end
    

    那么您的序列化程序将从这里继承而不是 ActiveModel::Serializer:

    class ArticleSerializer < SerializerWithSessionMetadata
      # ...
    end
    

    或者,您可以将其设置为包含在序列化程序中的模块:

    module SessionMetadataSerializer
      def self.included(klass)
        klass.attributes :token, :user
      end
    
      def token
        # ...
      end
    
      # ...
    end
    

    然后:

    class Api::V1::ArticleSerializer < ActiveModel::Serializer
      include SessionMetadataSerializer
      attributes :id, :author_id, :title, :description
    end
    

    【讨论】:

    • 谢谢@Jordan。对于令牌,在调用序列化程序的控制器方法中定义@token 就足够了,然后在超类序列化程序集中定义:def token@token end ?这就是这样做的方法吗?
    • 不,序列化程序无权访问控制器的实例变量。您使用的是哪个版本的 active_model_serializers?看起来serialization_options 是进入 0.9.4 的方式,如以下答案所述:stackoverflow.com/a/26780514
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-07
    • 2021-04-06
    • 2015-05-21
    • 1970-01-01
    • 1970-01-01
    • 2012-03-06
    • 2018-10-23
    相关资源
    最近更新 更多