diff --git a/lib/jsonschema.lua b/lib/jsonschema.lua index f3dffb4..2ca9c29 100644 --- a/lib/jsonschema.lua +++ b/lib/jsonschema.lua @@ -524,6 +524,13 @@ local function to_lua_code(var) return code .. "}" end +local function addRangeCheck(ctx, op, reference, msg) + ctx:stmt(sformat(' if %s %s %s then', ctx:param(1), op, reference)) + ctx:stmt(sformat(' return false, %s("expected %%s to be %s %s", %s)', + ctx:libfunc('string.format'), msg, reference, ctx:param(1))) + ctx:stmt( ' end') +end + generate_validator = function(ctx, schema) -- get type informations as they will be necessary anyway local datatype = ctx:localvartab(sformat('%s(%s)', @@ -896,33 +903,16 @@ generate_validator = function(ctx, schema) ctx:stmt(sformat('if %s == "number" then', datatype)) if schema.minimum then - local op = '<' - local msg = 'greater' - ctx:stmt(sformat(' if %s %s %s then', ctx:param(1), op, schema.minimum)) - ctx:stmt(sformat(' return false, %s("expected %%s to be %s than %s", %s)', - ctx:libfunc('string.format'), msg, schema.minimum, ctx:param(1))) - ctx:stmt( ' end') + addRangeCheck(ctx, '<', schema.minimum, 'at least') end - if schema.exclusiveMinimum then - ctx:stmt(sformat(' if %s %s %s then', ctx:param(1), "<=", schema.exclusiveMinimum)) - ctx:stmt(sformat(' return false, %s("expected %%s to be %s than %s", %s)', - ctx:libfunc('string.format'), 'strictly greater', schema.exclusiveMinimum, ctx:param(1))) - ctx:stmt( ' end') + addRangeCheck(ctx, '<=', schema.exclusiveMinimum, 'greater than') end - if schema.maximum then - ctx:stmt(sformat(' if %s %s %s then', ctx:param(1), ">", schema.maximum)) - ctx:stmt(sformat(' return false, %s("expected %%s to be %s than %s", %s)', - ctx:libfunc('string.format'), "smaller", schema.maximum, ctx:param(1))) - ctx:stmt( ' end') + addRangeCheck(ctx, '>', schema.maximum, 'at most') end - if schema.exclusiveMaximum then - ctx:stmt(sformat(' if %s %s %s then', ctx:param(1), ">=", schema.exclusiveMaximum)) - ctx:stmt(sformat(' return false, %s("expected %%s to be %s than %s", %s)', - ctx:libfunc('string.format'), 'strictly smaller', schema.exclusiveMaximum, ctx:param(1))) - ctx:stmt( ' end') + addRangeCheck(ctx, '>=', schema.exclusiveMaximum, 'smaller than') end local mof = schema.multipleOf