Skip to content

Commit c95481a

Browse files
committed
Added required fields support
1 parent afad4ef commit c95481a

File tree

3 files changed

+46
-1
lines changed

3 files changed

+46
-1
lines changed

example.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@ const stringify = fastJson({
1616
type: 'integer'
1717
},
1818
now: {
19-
type: 'string'
19+
type: 'string',
20+
required: true
2021
},
2122
reg: {
2223
type: 'string'

index.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,12 @@ function buildArray (schema, code, name) {
202202
function nested (laterCode, name, key, schema) {
203203
var code = ''
204204
var funcName
205+
if (schema.required) {
206+
code += `
207+
if (!obj.hasOwnProperty('${key.slice(1)}')) {
208+
throw new Error('${key} is required!')
209+
}`
210+
}
205211
const type = schema.type
206212
switch (type) {
207213
case 'null':

test.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,3 +254,41 @@ test('object with RexExp', (t) => {
254254
t.equal(obj.reg.source, new RegExp(JSON.parse(output).reg).source)
255255
t.ok(validate(JSON.parse(output)), 'valid schema')
256256
})
257+
258+
test('object with required field', (t) => {
259+
t.plan(3)
260+
261+
const schema = {
262+
title: 'object with required field',
263+
type: 'object',
264+
properties: {
265+
str: {
266+
type: 'string',
267+
required: true
268+
},
269+
num: {
270+
type: 'integer'
271+
}
272+
}
273+
}
274+
const stringify = build(schema)
275+
276+
try {
277+
stringify({
278+
str: 'string'
279+
})
280+
t.pass()
281+
} catch (e) {
282+
t.fail()
283+
}
284+
285+
try {
286+
stringify({
287+
num: 42
288+
})
289+
t.fail()
290+
} catch (e) {
291+
t.is(e.message, '.str is required!')
292+
t.pass()
293+
}
294+
})

0 commit comments

Comments
 (0)