diff --git a/README.md b/README.md index 722637d..b13c332 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ Tool for generation samples based on OpenAPI payload/response schema - Supports `allOf` - Supports `additionalProperties` - Uses `default`, `const`, `enum` and `examples` where possible -- Full array support: supports `minItems`, and tuples (`items` as an array) +- Good array support: supports `contains`, `minItems`, `maxItems`, and tuples (`items` as an array) - Supports `minLength`, `maxLength`, `min`, `max`, `exclusiveMinimum`, `exclusiveMaximum` - Supports the next `string` formats: - email diff --git a/src/samplers/array.js b/src/samplers/array.js index 2ef706c..d018fa4 100644 --- a/src/samplers/array.js +++ b/src/samplers/array.js @@ -2,20 +2,22 @@ import { traverse } from '../traverse'; export function sampleArray(schema, options = {}, spec, context) { const depth = (context && context.depth || 1); - let arrayLength = schema.minItems || 1; - if (Array.isArray(schema.items)) { - arrayLength = Math.max(arrayLength, schema.items.length); + let arrayLength = Math.min(schema.maxItems ?? Infinity, schema.minItems || 1); + // for the sake of simplicity, we're treating `contains` in a similar way to `items` + const items = schema.items || schema.contains; + if (Array.isArray(items)) { + arrayLength = Math.max(arrayLength, items.length); } let itemSchemaGetter = itemNumber => { if (Array.isArray(schema.items)) { - return schema.items[itemNumber] || {}; + return items[itemNumber] || {}; } - return schema.items || {}; + return items || {}; }; let res = []; - if (!schema.items) return res; + if (!items) return res; for (let i = 0; i < arrayLength; i++) { let itemSchema = itemSchemaGetter(i); diff --git a/test/unit/array.spec.js b/test/unit/array.spec.js index 664fe27..5c2acb8 100644 --- a/test/unit/array.spec.js +++ b/test/unit/array.spec.js @@ -11,6 +11,13 @@ describe('sampleArray', () => { it('should return elements of correct type', () => { res = sampleArray({items: {type: 'number'}}); expect(res).to.deep.equal([0]); + res = sampleArray({contains: {type: 'number'}}); + expect(res).to.deep.equal([0]); + }); + + it('should return correct number of elements based on maxItems', () => { + res = sampleArray({items: {type: 'number'}, maxItems: 0}); + expect(res).to.deep.equal([]); }); it('should return correct number of elements based on minItems', () => { @@ -18,7 +25,7 @@ describe('sampleArray', () => { expect(res).to.deep.equal([0, 0, 0]); }); - it('should correcly sample tuples', () => { + it('should correctly sample tuples', () => { res = sampleArray({items: [{type: 'number'}, {type: 'string'}, {}]}); expect(res).to.deep.equal([0, 'string', null]); });