Skip to content

Commit

Permalink
feat(schema) require only if_field in conditional fields
Browse files Browse the repository at this point in the history
This allows us to auto-fill the then_field with a default and
not require the presence of the if_field when performing
a partial update.
  • Loading branch information
hishamhm committed Sep 12, 2018
1 parent b741758 commit 57235ea
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
7 changes: 5 additions & 2 deletions kong/db/schema/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -495,7 +495,8 @@ Schema.entity_checkers = {
-- then_match = { required = true } }
-- ```
conditional = {
field_sources = { "if_field" },
field_sources = { "if_field", "then_field" },
required_fields = { ["if_field"] = true },
fn = function(entity, arg, schema)
local if_value = get_field(entity, arg.if_field)
local then_value = get_field(entity, arg.then_field) or null
Expand Down Expand Up @@ -909,10 +910,12 @@ local function run_entity_check(self, name, input, arg, full_check)
end

local all_nil = true
local required_fields = checker.required_fields
for _, fname in ipairs(fields_to_check) do
local value = get_field(input, fname)
if value == nil then
if not checker.run_with_missing_fields then
if not (checker.run_with_missing_fields or
(required_fields and not required_fields[fname])) then
local err = validation_errors.REQUIRED_FOR_ENTITY_CHECK
set_field(field_errors, fname, err)
ok = false
Expand Down
12 changes: 10 additions & 2 deletions spec/01-unit/000-new-dao/01-schema/01-schema_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -1430,9 +1430,12 @@ describe("schema", function()
redis_host = "example.com",
redis_port = 80
}))
assert.falsy(Test:validate_update({
assert.truthy(Test:validate_update({
policy = "bla",
}))
assert.falsy(Test:validate_update({
policy = "redis",
}))
end)

it("supports entity checks on nested fields", function()
Expand Down Expand Up @@ -1476,6 +1479,11 @@ describe("schema", function()
}
}))
assert.falsy(Test:validate_update({
config = {
policy = "redis",
}
}))
assert.truthy(Test:validate_update({
config = {
policy = "bla",
}
Expand Down Expand Up @@ -1536,7 +1544,7 @@ describe("schema", function()
{ d = { type = "integer" }, },
{ e = { type = "boolean" }, },
{ f = { type = "string" }, },
{ g = { type = "record", fields = {} }, },
{ g = { type = "record", fields = {} }, },
{ h = { type = "map", keys = {}, values = {} }, },
}
})
Expand Down

0 comments on commit 57235ea

Please sign in to comment.