Skip to content
This repository has been archived by the owner on Jun 30, 2022. It is now read-only.

Adding example reader #11

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 39 additions & 4 deletions lib/generate.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,40 @@
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 ) {
if ( schema.type === 'string' && name.match( /id$/i ) ) {
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
if ( schema.enum ) {
return options.chance.pickone( schema.enum );
}



// when no typehints are found, try to generate meaningful data
// based on 'format'
switch ( schema.format ) {
Expand All @@ -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'
Expand All @@ -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 ) {
Expand All @@ -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;

Expand Down