Как проверить массив различных объектов с помощью гема с сухой схемой
Учитывая, что у меня есть такой объект JSON, имеющий массив различных объектов, таких как:
{
"array": [
{
"type": "type_1",
"value": 5
},
{
"type": "type_2",
"kind": "person"
}
]
}
Согласно проверке схемы JSON, я могу проверить эту схему, используя это определение схемы JSOM:
{
"type": "object",
"properties": {
"array": {
"type": "array",
"items": {
"oneOf": [
{
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": [
"type_1"
]
},
"value": {
"type": "integer",
"enum": [
5
]
}
}
},
{
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": [
"type_2"
]
},
"kind": {
"type": "string",
"enum": [
"person"
]
}
}
}
]
}
}
}
}
Как я могу проверить входной JSON с помощью гема сухой схемы? У тебя есть идеи?
1 ответ
Чтобы решить вашу проблему, попробуйте этот код:
class TestContract < Dry::Validation::Contract
FirstHashSchema = Dry::Schema.Params do
required(:type).filled(:string)
required(:value).filled(:integer)
end
SecondHashSchema = Dry::Schema.Params do
required(:type).filled(:string)
required(:kind).filled(:string)
end
params do
required(:array).array do
# FirstHashSchema.or(SecondHashSchema) also works
schema FirstHashSchema | SecondHashSchema
end
end
end
valid_input = {
array: [
{
type: 'type_1',
value: 5
},
{
type: 'type_2',
kind: 'person'
}
]
}
TestContract.new.call(valid_input) #=> Dry::Validation::Result{:array=>[...] errors={}}
invalid_input = {
array: [
{
type: 'type_1',
bad_key: 5
},
{
type: 'type_2',
kind: 'person'
}
]
}
TestContract.new.call(invalid_input) #=> Dry::Validation::Result{:array=>[...] errors={:array=>{0=>{:or=>[...]}}}
Главное здесь — метод#schema
. Документация