2021-01-07

rails Grape验证参数(params)一些其他用法

目的:通过 学习grape 参数的一些验证方式,可以很大程度的减少在代码中的一些验证逻辑,其实很多验证通过grape自带的params 的验证就可以实现了。
  • grape 支持的参数类型:Integer、Float、BigDecimal、Numeric、Date、DateTime、Time、Boolean、String、Symbol、Rack::Multipart::UploadedFile (alias File)、JSON

  • grape 参数除了常规用法以外,还有一些其他用法。
    参数写好,其实可以省去好多验证方法。

#可以采用正则表达书进行验证
params do 
	optional :text, type: String, regexp: /\A[a-z]+\z/   
	optional :format, type: Symbol, values: [:mp3, :wav, :aac, :ogg], default: :mp3  # 可以设置值,包括默认值
end
# json 字符串样式
params do
  requires :json, type: JSON do
    requires :int, type: Integer, values: [1, 2, 3]  # 可以传一个json: '{"int":1}') 或者 json: '[{"int":"1"}]') 
  end
end
# 如果类型比较多,可以写成这样。
params do
  requires :status_code, types: [Integer, String, Array[Integer, String]] # status_code: 'OK_GOOD'、status_code: 300、status_code: %w(404 NOT FOUND)
end 
# 数组包hash
params do
  optional :preferences, type: Array do
    requires :key
    requires :value
  end
# 只有 hash
  requires :name, type: Hash do
    requires :first_name
    requires :last_name
  end
end
# 这种可以对一个可选的类型进行验证,只要传了shelf_id,就必须传一个 bin_id
params do
  optional :shelf_id, type: Integer
  given :shelf_id do
    requires :bin_id, type: Integer
  end
end
# 也可以嵌套代码在params 中
params do
  optional :category
  given category: ->(val) { val == 'foo' } do
    requires :description
  end
end
# 这种是带重命名的,可以用作前端传的参数和后端处理参数不一致的情况
params do
  optional :category, as: :type
  given type: ->(val) { val == 'foo' } do
    requires :description
  end
end
# 可以对可选参数进行判断,虽然是可选,但是只要传了就不能为空。
params do
  optional :first_name, allow_blank: false
end
# 定义这两个参数不同时出现,是互斥的
params do
  optional :beer
  optional :wine
  mutually_exclusive :beer, :wine
end
# 定义这两个参数只能选择一个。
params do
  optional :beer
  optional :wine
  exactly_one_of :beer, :wine
end
 # 定义这几个参数至少选择一个
params do
  optional :beer
  optional :wine
  optional :juice
  at_least_one_of :beer, :wine, :juice
end
# 要不都选,要不都不选
params do
  optional :beer
  optional :wine
  optional :juice
  all_or_none_of :beer, :wine, :juice
end
#支持多个验证方式,同时可以设置验证失败后的返回信息
params do
  requires :name, values: { value: 1..10, message: 'not in range from 1 to 10' }, allow_blank: { value: false, message: 'cannot be blank' }, regexp: { value: /^[a-z]+$/, message: 'format is invalid' }, message: 'is required'
end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值