Skip to content

Commit 2dbd148

Browse files
authored
Merge pull request #4 from mcollina/fix-required-field
Fix required field
2 parents ec7bdf0 + 096a227 commit 2dbd148

File tree

4 files changed

+14
-14
lines changed

4 files changed

+14
-14
lines changed

README.md

+7-7
Original file line numberDiff line numberDiff line change
@@ -69,13 +69,13 @@ And nested ones, too.
6969

7070
#### Specific use cases
7171

72-
| Instance | Serialized as |
73-
| -----------|---------------------------------------------|
72+
| Instance | Serialized as |
73+
| -----------|------------------------------|
7474
| `Date` | `string` via `toISOString()` |
75-
| `RegExp` | `string` |
75+
| `RegExp` | `string` |
7676

7777
#### Required
78-
You can set specific fields of an object as `required` in your schema, by adding `required: true` inside the key properties.
78+
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.
7979
Example:
8080
```javascript
8181
const schema = {
@@ -86,10 +86,10 @@ const schema = {
8686
type: 'string'
8787
},
8888
mail: {
89-
type: 'string',
90-
required: true
89+
type: 'string'
9190
}
92-
}
91+
},
92+
required: ['mail']
9393
}
9494
```
9595
If the object to stringify has not the required field(s), `fast-json-stringify` will throw an error.

example.js

+3-3
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,13 @@ const stringify = fastJson({
1616
type: 'integer'
1717
},
1818
now: {
19-
type: 'string',
20-
required: true
19+
type: 'string'
2120
},
2221
reg: {
2322
type: 'string'
2423
}
25-
}
24+
},
25+
required: ['now']
2626
})
2727

2828
console.log(stringify({

index.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ function buildObject (schema, code, name) {
158158
`
159159
}
160160

161-
if (schema.properties[key].required) {
161+
if (schema.required && schema.required.indexOf(key) !== -1) {
162162
code += `
163163
} else {
164164
throw new Error('${key} is required!')

test.js

+3-3
Original file line numberDiff line numberDiff line change
@@ -263,13 +263,13 @@ test('object with required field', (t) => {
263263
type: 'object',
264264
properties: {
265265
str: {
266-
type: 'string',
267-
required: true
266+
type: 'string'
268267
},
269268
num: {
270269
type: 'integer'
271270
}
272-
}
271+
},
272+
required: ['str']
273273
}
274274
const stringify = build(schema)
275275

0 commit comments

Comments
 (0)