diff --git a/example.js b/example.js index c9455e86..d4dc1db4 100644 --- a/example.js +++ b/example.js @@ -16,7 +16,8 @@ const stringify = fastJson({ type: 'integer' }, now: { - type: 'string' + type: 'string', + required: true }, reg: { type: 'string' diff --git a/index.js b/index.js index 20ff97ce..3df51134 100644 --- a/index.js +++ b/index.js @@ -202,6 +202,12 @@ function buildArray (schema, code, name) { function nested (laterCode, name, key, schema) { var code = '' var funcName + if (schema.required) { + code += ` + if (!obj.hasOwnProperty('${key.slice(1)}')) { + throw new Error('${key} is required!') + }` + } const type = schema.type switch (type) { case 'null': diff --git a/test.js b/test.js index 8e39c72a..a69d5ee5 100644 --- a/test.js +++ b/test.js @@ -254,3 +254,41 @@ test('object with RexExp', (t) => { t.equal(obj.reg.source, new RegExp(JSON.parse(output).reg).source) t.ok(validate(JSON.parse(output)), 'valid schema') }) + +test('object with required field', (t) => { + t.plan(3) + + const schema = { + title: 'object with required field', + type: 'object', + properties: { + str: { + type: 'string', + required: true + }, + num: { + type: 'integer' + } + } + } + const stringify = build(schema) + + try { + stringify({ + str: 'string' + }) + t.pass() + } catch (e) { + t.fail() + } + + try { + stringify({ + num: 42 + }) + t.fail() + } catch (e) { + t.is(e.message, '.str is required!') + t.pass() + } +})