为什么 Grape API 参数块中的 require 指令没有被观察到?

问题描述 投票:0回答:1

我有一个 Grape API 类 Customer 子类化 Grape::API。指定为

requires
的参数尚未得到验证。如果发出的请求没有这些参数,则代码将继续执行而不会引发异常。如何启用需要验证?

module API
  module V1
    # API interface for users
    class Customers < Grape::API
      include API::V1::Defaults

      helpers do
        def customer_options(params)
          {
            user_id: params.user_id,
            phone: params.phone,
            date_of_birth: params.date_of_birth
          }
        end
      end

      resource :customers do
        desc "Create a customer"
        post do
          params do
            requires :user_id, type: Integer, desc: "ID of associated user record", allow_blank: false
            requires :phone, type: String, desc: "Applicant's phone number", allow_blank: false
            requires :date_of_birth, type: String, desc: "Applicant's date of birth", allow_blank: false
          end

          options = customer_options(permitted_params)

          customer = nil
          Customer.transaction do
            customer = Customer.create!(options)
          end
          result = {
            id: customer.id,
            phone: customer.phone,
            user_id: customer.user_id
          }
          result["date_of_birth"] = customer.date_of_birth if
            customer.date_of_birth.present?
          result
        end
      end
    end
  end
end
ruby-on-rails ruby-grape
1个回答
0
投票

仔细与其他示例进行比较后,我意识到我将参数定义放在了 post 块中,这是行不通的。拆分它们使验证能够正确识别和运行。

resource :customers do
        desc "Create a customer"
        params do
          requires :user_id, type: Integer, desc: "ID of associated user record", allow_blank: false
          requires :phone, type: String, desc: "Applicant's phone number", allow_blank: false
          requires :date_of_birth, type: String, desc: "Applicant's date of birth", allow_blank: false
        end
        post do
          options = customer_options(permitted_params)
© www.soinside.com 2019 - 2024. All rights reserved.