Grape API参数格式错误

huangapple go评论46阅读模式
英文:

Grape API malformed parameters

问题

I'm trying to make a post endpoint, with multiple nested parameters but the params are not as expected

I have the following parameters definitions for the endpoint:

params do
  requires :p2 do
    optional :p3
    requires :p4, as: :p4_new
    requires :p5, as: :p5_new do
      requires :p6, as: :p6_new
    end
  end
end

So I put a debugger in the first line of the endpoint and I am expecting the parameters to look like this:

{
  "p2": {
    "p3": 1,
    "p4_new": "Ceva nume",
    "p5_new": {
      "p6_new": 1
    }
  }
}

But the actual parameters are malformed, it gives me both the newly named parameters and the old name for the parameters, in a chaotic order. It doesn't make any sense. Does anyone know what is going on here?

英文:

I'm trying to make a post endpoint, with multiple nested parameters but the params are not as expected

I have the following parameters definitions for the endpoint:

params do
  requires :p2 do
    optional :p3
    requires :p4, as: :p4_new
    requires :p5, as: :p5_new do
      requires :p6, as: :p6_new
    end
  end
end

So I put a debugger in the first line of the endpoint and I am expecting the parameters to look like this:

{
  "p2": {
    "p3": 1,
    "p4_new": "Ceva nume",
    "p5_new": {
      "p6_new": 1,
    }
  }
}

But the actual parameters are malformed, it gives me both the newly named parameters and the old name for the parameters, in a chaotic order.
It doesn't make any sense. Does anyone know what is going on here?

答案1

得分: 1

你看到了paramsdeclared(params)之间的区别。有关重命名参数的文档指定,如果您只想要重命名后的参数,您需要使用declared(params)

您可以使用as来重命名参数,这在重构现有API时非常有用:

resource :users do
  params do
    requires :email_address, as: :email
    requires :password
  end
  post do
    User.create!(declared(params)) # User接受email和password
  end
end

传递给as的值将在调用declared(params)时成为键。

我假设您正在调用params,这会将原始参数和重命名后的参数合并在一起。切换到declared(params)以获取只有重命名后的参数。

英文:

You're seeing the difference between params and declared(params). The documentation on renaming params specifies that if you want only the renamed parameters that you need to use declared(params):

> You can rename parameters using as, which can be useful when refactoring existing APIs:

resource :users do
  params do
    requires :email_address, as: :email
    requires :password
  end
  post do
    User.create!(declared(params)) # User takes email and password
  end
end

> The value passed to as will be the key when calling declared(params)

I assume that you're calling params which is giving you both the original and the renamed parameters merged together. Switch to declared(params) to get just the renamed parameters.

huangapple
  • 本文由 发表于 2023年3月31日 21:31:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75899122.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定