Skip to content

Commit

Permalink
feat(obj): allow to add additional properties
Browse files Browse the repository at this point in the history
  • Loading branch information
peyerluk committed Jul 5, 2018
1 parent 97bd2e6 commit 145e931
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 1 deletion.
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,22 @@ output = {
}
```

Add title and description:
```js
ms.obj({
displayName: 'string',
}, {title: 'Title', description: 'Desc.'})
```

Add dependencies:
```js
ms.obj({
creditCard: 'string',
address: 'string'
}, {dependencies: {creditCard: 'address'}})
```


## Arrays

```js
Expand Down
14 changes: 13 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,16 @@ module.exports = {
// Methods
// -------

obj (microschema = {}, {strict, required} = {}) {
obj (microschema = {}, {strict, required, title, description, dependencies} = {}) {
const jsonSchema = {
type: 'object',
properties: {}
}

if (title) jsonSchema.title = title
if (description) jsonSchema.description = description
if (strict) jsonSchema.additionalProperties = false
if (dependencies) setDependencies(jsonSchema, dependencies)

if (required) {
if (!Array.isArray(required)) throw new Error("'required' must be an array")
Expand Down Expand Up @@ -196,3 +199,12 @@ function isString (str) {
function isNumber (nr) {
return typeof nr === 'number'
}

function setDependencies (jsonSchema, dependencies) {
const formattedDeps = {}
for (const prop in dependencies) {
const value = dependencies[prop]
formattedDeps[prop] = isString(value) ? [value] : value
}
jsonSchema.dependencies = formattedDeps
}
38 changes: 38 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,44 @@ const ms = require('./index')
const test = require('ava').test
const assert = require('assert')

test('obj() creates an object with title and description', function (t) {
const schema = ms.obj({
displayName: 'string'
}, {
title: 'Title',
description: 'Desc.'
})

assert.deepEqual(schema, {
type: 'object',
properties: {
displayName: {type: 'string'}
},
title: 'Title',
description: 'Desc.'
})
})

test('obj() creates an object with dependencies', function (t) {
const schema = ms.obj({
name: 'string',
displayName: 'string'
}, {
dependencies: {name: 'displayName'}
})

assert.deepEqual(schema, {
type: 'object',
properties: {
name: {type: 'string'},
displayName: {type: 'string'}
},
dependencies: {
name: ['displayName']
}
})
})

test('strictObj() creates an object with a single property', function (t) {
const schema = ms.strictObj({foo: 'string'})

Expand Down

0 comments on commit 145e931

Please sign in to comment.