【问题标题】:Enforce that a Grape Entity always returns an array?强制葡萄实体总是返回一个数组?
【发布时间】:2017-07-18 17:49:49
【问题描述】:

如何强制我的 Grape 实体始终返回一个数组(集合),即使它只是一个单一对象?我听说有些人创建了一个在端点内部调用的辅助方法,但我没有在网上找到任何人这样做的例子。

Entity 的默认功能是,如果只返回一个文档(mongoid 对象),它就会返回一个对象。如果返回了一个文档集合,那么它会返回一个数组,我不希望我的客户端应用程序每次都必须检查是否从我的 API 返回了一个对象或数组。

## Resource (HTTP Endpoint)
desc 'List departments a user can and cannot access'
params do
  requires :user_id
end
get :department_access do
  @user = BACKBONE::User.find(@access_key.user_id)
  requires_admin!
  user = BACKBONE::User.find(params[:user_id])
  can_access = BACKBONE::Department.user_can_access(user)
  no_access = BACKBONE::Department.user_cannot_access(user)
  present_success can_access
  present :can_access, can_access, with: BACKBONE::Entities::DepartmentBase
  present :no_access, no_access, with: BACKBONE::Entities::DepartmentBase
end

-

## Entity
module BACKBONE
  module Entities
    class DepartmentBase < BACKBONE::Entities::Mongoid
      expose :name
      expose :prefix
      with_options(format_with: :mongo_id) do
        expose :company_id
      end
    end
  end
end

JSON 响应

{
    "status": "success",
    "request_time": 0.009812,
    "records": 1,
    "can_access": {
        "id": "59699d1a78cee4f8d07528fc",
        "created_at": "2017-07-14T21:42:02.666-07:00",
        "updated_at": "2017-07-14T21:42:02.666-07:00",
        "name": "Tenant Improvement",
        "prefix": "CACC",
        "company_id": "596927fb670f6eec21c4f409"
    },
    "no_access": {
        "id": "59699cca78cee4f8d07528fb",
        "created_at": "2017-07-14T21:40:42.005-07:00",
        "updated_at": "2017-07-14T21:40:42.005-07:00",
        "name": "Field Operations",
        "prefix": "CACC",
        "company_id": "596927fb670f6eec21c4f409"
    }
}

【问题讨论】:

    标签: ruby mongoid grape


    【解决方案1】:

    我和一个同事想出了一个带有助手的解决方案,创建一个总是返回数组的助手方法:

    def present_array(key, data, entity)
      d = (data.class.respond_to? :count) ? [data] : data
      d = [] if d.nil?
      present key, d, entity
    end
    

    【讨论】:

      猜你喜欢
      • 2015-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多