From d978aa5cbffe4638ad0e075e5b3bab0a46d60670 Mon Sep 17 00:00:00 2001 From: Mateus Fernandes Malvar Date: Mon, 7 Oct 2019 16:44:02 -0300 Subject: [PATCH] Adding example reader --- lib/generate.js | 43 +++++++++++++++++++++++++++++++++++++++---- 1 file changed, 39 insertions(+), 4 deletions(-) diff --git a/lib/generate.js b/lib/generate.js index 110b658..a282485 100644 --- a/lib/generate.js +++ b/lib/generate.js @@ -1,5 +1,17 @@ var _ = require( 'lodash' ); - +//when there is example it is setted +//case the example is a array, choose one value ramdomically +let enableExample = (schema,options)=>{ + if(schema.example){ + if(Array.isArray(schema.example)){ + //random position, because we cannot garantee we always have the method pickone (from options.chance) + let position = Math.floor(Math.random()*schema.example.length); + return schema.example[position]; + } + return schema.example; + } + return false; +} module.exports = { id: function ( name, schema, options ) { @@ -7,9 +19,13 @@ module.exports = { return options.chance.guid(); } }, - + string: function ( name, schema, options ) { - + let example = enableExample(schema,options); + if(example){ + return example; + } + if ( schema.type !== 'string' ) return; // pick one random element from an enum @@ -17,6 +33,8 @@ module.exports = { return options.chance.pickone( schema.enum ); } + + // when no typehints are found, try to generate meaningful data // based on 'format' switch ( schema.format ) { @@ -34,6 +52,11 @@ module.exports = { number: function ( name, schema, options ) { + let example = enableExample(schema,options); + if(example){ + return example; + } + if ( schema.type !== 'number' ) return; // supported formats are 'float' and 'double' @@ -43,17 +66,25 @@ module.exports = { }, integer: function ( name, schema, options ) { + let example = enableExample(schema,options); + if(example){ + return example; + } if ( schema.type !== 'integer' ) return; return options.chance.integer( { min: 0, max: 4096 } ); }, boolean: function ( name, schema, options ) { + let example = enableExample(schema,options); + if(example){ + return example; + } if ( schema.type !== 'boolean' ) return; return options.chance.bool(); }, array: function ( name, schema, options, gen, depth ) { - + // Limitation: our modification do not accept array inside array. if ( schema.type !== 'array' ) return; if ( depth > options.maxDepth ) { @@ -75,6 +106,10 @@ module.exports = { }, object: function ( name, schema, options, gen, depth ) { + let example = enableExample(schema,options); + if(example){ + return example; + } if ( schema.type && schema.type !== 'object' ) return;