From 433e35c9076e1a5a141eb5f22510b2ffd7fc27d8 Mon Sep 17 00:00:00 2001 From: delvedor Date: Fri, 16 Sep 2016 20:54:07 +0200 Subject: [PATCH 1/2] Updated required field according to the json schema spec. --- index.js | 2 +- test.js | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/index.js b/index.js index bc92ca87..7a38ac84 100644 --- a/index.js +++ b/index.js @@ -158,7 +158,7 @@ function buildObject (schema, code, name) { ` } - if (schema.properties[key].required) { + if (schema.required && schema.required.indexOf(key) !== -1) { code += ` } else { throw new Error('${key} is required!') diff --git a/test.js b/test.js index 69edd878..9bfe0a58 100644 --- a/test.js +++ b/test.js @@ -263,13 +263,13 @@ test('object with required field', (t) => { type: 'object', properties: { str: { - type: 'string', - required: true + type: 'string' }, num: { type: 'integer' } - } + }, + required: ['str'] } const stringify = build(schema) From 096a227d90c70cbd40116139a2a0a356c286d259 Mon Sep 17 00:00:00 2001 From: delvedor Date: Fri, 16 Sep 2016 20:54:31 +0200 Subject: [PATCH 2/2] Updated docs and examples --- README.md | 14 +++++++------- example.js | 6 +++--- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index af6c683a..fbff1278 100644 --- a/README.md +++ b/README.md @@ -69,13 +69,13 @@ And nested ones, too. #### Specific use cases -| Instance | Serialized as | -| -----------|---------------------------------------------| +| Instance | Serialized as | +| -----------|------------------------------| | `Date` | `string` via `toISOString()` | -| `RegExp` | `string` | +| `RegExp` | `string` | #### Required -You can set specific fields of an object as `required` in your schema, by adding `required: true` inside the key properties. +You can set specific fields of an object as required in your schema, by adding the field name inside the `required` array in your schema. Example: ```javascript const schema = { @@ -86,10 +86,10 @@ const schema = { type: 'string' }, mail: { - type: 'string', - required: true + type: 'string' } - } + }, + required: ['mail'] } ``` If the object to stringify has not the required field(s), `fast-json-stringify` will throw an error. diff --git a/example.js b/example.js index d4dc1db4..3ac66b05 100644 --- a/example.js +++ b/example.js @@ -16,13 +16,13 @@ const stringify = fastJson({ type: 'integer' }, now: { - type: 'string', - required: true + type: 'string' }, reg: { type: 'string' } - } + }, + required: ['now'] }) console.log(stringify({