Grape Entity - 如何返回嵌套值而不是键值对?

时间:2017-07-11 23:49:07

标签: ruby mongoid grape

我有一个POST auth端点,它返回一个令牌和用户对象数据,以及一些元数据。

我遇到了一个问题因为我没有尝试从我的实体返回一个对象,我只想返回一个值...

以下是来自我的终端的示例JSON响应:

{
  "status": "success",
  "request_time": 0.108006,
  "records": 1,
  "msg": "some msg",
  "user": {
    "id": "someidstringformongodb",
    "created_at": "2017-07-10T17:15:15.334-07:00",
    "updated_at": "2017-07-10T17:15:15.334-07:00",
    "active": true,
    "email": "email@test.com",
    "first_name": "John",
    "last_name": "Doe",
    "suffix": null,
    "title": "Cool Title",
    "admin": false,
    "phone": "777-777-7777"
  },
  "access_key": {
    "token": "xxxsomerandomtokenxxx"
  }
}

所需的JSON响应

{
  // ...
  "user": {
    //...
  },
  "access_key": "xxxsomerandomtokenxxx"
}

// or

{
  // ...
  "user": {
    //...
  },
  "token": "xxxsomerandomtokenxxx"
}

相关的终端代码

post '/' do
  email_pattern = /^#{ sanitize_user_input(params[:email]) }$/i
  user = SomeModule::User.find_by(email: email_pattern)
  error!('Invalid email/password combination') if user.nil?
  error!('Invalid email/password combination') unless user.password == params[:password]
  error!('This account is no longer active') unless user.active
  access_key = SomeModule::AccessKey.new_key_for_user(user)
  access_key.save
  present_success user, "some msg"
  present :user, user, with: SomeModule::Entities::UserBase

  ## what should happen to this, in order to return only the value instead of an object?
  present :access_key, access_key, with: SomeModule::Entities::AccessKey
end

相关实体代码

class AccessKey < Grape::Entity
  expose :token
end

0 个答案:

没有答案