Skip to content

Instantly share code, notes, and snippets.

@gszr
Created November 21, 2024 13:59
Show Gist options
  • Save gszr/3174877bc300c3f145a23dd7600b326e to your computer and use it in GitHub Desktop.
Save gszr/3174877bc300c3f145a23dd7600b326e to your computer and use it in GitHub Desktop.
Kong schema validation
setmetatable(_G, nil)
local MetaSchema = require "kong.db.schema.metaschema"
local s1 = {
name = "schema",
primary_key = {},
fields = {
{ js_enabled = { type = "boolean" }},
{ sql_enabled = { type = "boolean" }},
{ custom = { type = "array", elements = { type = "record", fields = {{ name = { type = "string", } } } }}},
},
entity_checks = {
{ at_least_one_of = { "js_enabled", "sql_enabled", "custom" } },
},
}
assert(MetaSchema:validate(s1))
local Entity = require "kong.db.schema.entity"
local S1 = Entity.new(s1)
-- ok: all bundled + custom
assert(S1:validate({js_enabled = true, sql_enabled = true, custom = {}}))
-- ok: only bundled
assert(S1:validate({js_enabled = true, sql_enabled = true}))
-- ok: only custom
assert(S1:validate({custom = {{ name = "foo" }}}))
-- not ok: custom without at least one element
local ok, err = S1:validate({custom = {}})
print(require"inspect"(err))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment