Skip to content
Permalink
Browse files

feat(schema) allow partial update of record fields

  • Loading branch information...
hishamhm committed Jul 27, 2018
1 parent 7864171 commit 05adc40fb690f2c1105ae1f2ace45f83eabb686c
Showing with 47 additions and 3 deletions.
  1. +28 −3 kong/db/schema/init.lua
  2. +19 −0 spec/01-unit/000-new-dao/01-schema/01-schema_spec.lua
@@ -468,6 +468,24 @@ Schema.entity_checkers = {
}


local function memoize(fn)
local cache = setmetatable({}, { __mode = "k" })
return function(k)
if cache[k] then
return cache[k]
end
local v = fn(k)
cache[k] = v
return v
end
end


local get_field_schema = memoize(function(field)
return Schema.new(field)
end)


-- Forward declaration
local validate_fields

@@ -568,7 +586,7 @@ function Schema:validate_field(field, value)
return nil, validation_errors.SCHEMA_MISSING_ATTRIBUTE:format("fields")
end

local field_schema = Schema.new(field)
local field_schema = get_field_schema(field)
-- TODO return nested table or string?
local copy = field_schema:process_auto_fields(value, "insert")
local ok, err = field_schema:validate(copy)
@@ -686,7 +704,7 @@ end
-- @param entity The entity object where key `k` is missing.
local function handle_missing_field(k, field, entity)
if field.default ~= nil then
entity[k] = field.default
entity[k] = tablex.deepcopy(field.default)
return
end

@@ -1028,7 +1046,9 @@ end

--- Given a table, update its fields whose schema
-- definition declares them as `auto = true`,
-- based on its CRUD operation context.
-- based on its CRUD operation context, and set
-- defaults for missing values when the CRUD context
-- is "insert".
-- This function encapsulates various "smart behaviors"
-- for value creation and update.
-- @param input The table containing data to be processed.
@@ -1064,6 +1084,11 @@ function Schema:process_auto_fields(input, context)
output[key] = make_array(field_value)
elseif field_type == "set" then
output[key] = make_set(field_value)
elseif field_type == "record" then
if field_value ~= null then
local field_schema = get_field_schema(field)
output[key] = field_schema:process_auto_fields(field_value, context)
end
end

elseif context ~= "update" then
@@ -1525,6 +1525,24 @@ describe("schema", function()
{ f = { type = "number" }, },
},
default = { f = 123 } }, },
{ nested_record = {
type = "record",
default = {
r = {
a = "nr",
b = 123,
}
},
fields = {
{ r = {
type = "record",
fields = {
{ a = { type = "string" } },
{ b = { type = "number" } }
}
} }
}
} }
}
})
check_all_types_covered(Test.fields)
@@ -1537,6 +1555,7 @@ describe("schema", function()
assert.same("foo", data.f)
assert.same({ foo = 1, bar = 2 }, data.g)
assert.same({ f = 123 }, data.h)
assert.same({ r = { a = "nr", b = 123, }}, data.nested_record)
end)

it("honors 'false' as a default", function()

0 comments on commit 05adc40

Please sign in to comment.
You can’t perform that action at this time.