Coder Social home page Coder Social logo

omerts / json-schema-faker Goto Github PK

View Code? Open in Web Editor NEW

This project forked from json-schema-faker/json-schema-faker

0.0 2.0 0.0 1.27 MB

JSON-Schema + Faker

Home Page: http://json-schema-faker.js.org/

License: MIT License

JavaScript 78.73% CoffeeScript 21.27%

json-schema-faker's Introduction

Fake your schemas!

Build Status NPM version Coverage Status

Dependency Status devDependency Status

Use JSON Schema along with fake generators to provide consistent fake data for your system. Note that json-schema-faker supports (currently) the JSON-Schema specification draft-04 only.

Online demo

See online demo.

Install

Install json-schema-faker with npm:

npm install json-schema-faker --save-dev

Example usage

var jsf = require('json-schema-faker');

var schema = {
  type: 'object',
  properties: {
    user: {
      type: 'object',
      properties: {
        id: {
          $ref: '#/definitions/positiveInt'
        },
        name: {
          type: 'string',
          faker: 'name.findName'
        },
        email: {
          type: 'string',
          format: 'email',
          faker: 'internet.email'
        }
      },
      required: ['id', 'name', 'email']
    }
  },
  required: ['user'],
  definitions: {
    positiveInt: {
      type: 'integer',
      minimum: 0,
      minimumExclusive: true
    }
  }
};

var sample = jsf(schema);

console.log(sample.user.name);
// output: John Doe

Supported keywords

  • $ref — Resolve internal references only, and/or external if provided.
  • required — All required properties are guaranteed, if not can be omitted.
  • pattern — Generate samples based on RegExp values.
  • format — Core formats only: date-time, email, hostname, ipv4, ipv6 and uri.
  • enum — Returns any of these enumerated values.
  • minLength/maxLength — Applies length constraints to string values.
  • minimum/maximum — Applies constraints to numeric values.
  • exclusiveMinimum/exclusiveMaximum — Adds exclusivity for numeric values.
  • multipleOf — Multiply constraints for numeric values.
  • items — Support for subschema and fixed item values.
  • minItems/maxItems — Adds length constraints for array items.
  • uniqueItems — Applies uniqueness constraints for array items.
  • additionalItems — Partially supported (?)
  • allOf/oneOf/anyOf — Subschema combinators.
  • properties — Object properties to be generated.
  • minProperties/maxProperties — Adds length constraints for object properties.
  • patternProperties — RegExp-based object properties.
  • additionalProperties — Partially supported (?)
  • dependencies — Not supported yet (?)
  • not — Not supported yet (?)

Using references

Inline references are fully supported (json-pointers) but external can't be resolved by json-schema-faker.

In order to achieve that you can use refaker and then use the resolved schemas:

var schema = {
  type: 'object',
  properties: {
    someValue: {
      $ref: 'otherSchema'
    }
  }
};

var refs = [
  {
    id: 'otherSchema',
    type: 'string'
  }
];

var sample = jsf(schema, refs);

console.log(sample.someValue);
// output: voluptatem

Faking values

json-schema-faker has built-in generators for core-formats, Faker.js and Chance.js are also supported.

You can use faker or chance properties but they are optional:

{
  "type": "string",
  "faker": "internet.email"
}

The above schema will invoke:

require('faker').internet.email();

Another example is passing arguments to the generator:

{
  "type": "string",
  "chance": {
    "email": {
      "domain": "fake.com"
    }
  }
}

And will invoke:

var Chance = require('chance'),
  chance = new Chance();

chance.email({ "domain": "fake.com" });

If you pass an array, they will be used as raw arguments.

Note that both generators has higher precedence than format.

You can also use standard JSON Schema keywords, e.g. pattern:

{
  "type": "string",
  "pattern": "yes|no|maybe|i don't know"
}

Custom formats

Additionally, you can add custom generators for those:

jsf.formats('semver', function(gen, schema) {
  return gen.randexp('^\\d\\.\\d\\.\\d{1,2}$');
});

Now that format can be generated:

{
  "type": "string",
  "format": "semver"
}

Usage:

  • formats() — Return all registered formats (custom only)
  • formats(obj) — Register formats by key/value → name/callback
  • formats(name) — Returns that format generator (undefined if not exists)
  • formats(name, callback) — Register a custom format by name/callback

Callback:

  • gen (object) — Built in generators
    • faker (object) — Faker.js instance
    • chance (object) — Chance.js instance
    • randexp (function) — Randexp generator
  • schema (object) — The schema for input

Note that custom generators has lower precedence than core ones.

Extending dependencies

You may extend Faker.js:

var jsf = require('json-schema-faker');

jsf.extend('faker', function(faker){
  faker.locale = "de"; // or any other language
  faker.custom = {
    statement: function(length) {
      return faker.name.firstName() + " has " + faker.finance.amount() + " on " + faker.finance.account(length) + ".";
    }
  };
  return faker;
});

var schema = {
  "type": "string",
  "faker": {
    "custom.statement": [19]
  }
}

var sample = jsf(schema);

... and Chance.js, using built-in chance.mixin function:

var jsf = require('json-schema-faker');

jsf.extend('chance', function(chance){
  chance.mixin({
    'user': function() {
      return {
        first: chance.first(),
        last: chance.last(),
        email: chance.email()
      };
    }
  });

  return chance;
});

var schema = {
  "type": "string",
  "chance": "user"
}

var sample = jsf(schema);

The first parameter of extend function is the generator name (faker or chance). The second one is the function that accepts the dependency library; the function alters the library and returns it.

Inferred Types

JSON Schema does not require you to provide the type property for your JSON Schema documents and document fragments.

But since jsf uses the type property to create the proper fake data, we attempt to infer the type whenever it is not provided. We do this based on the JSON Schema validation properties you use.

Now this means that if you do not use any of the JSON Schema validation properties, json-schema-faker will not be able to infer the type for you and you will need to explicitly set your type manually.)

Below is the list of JSON Schema validation properties and the inferred type based on the property:

array

  • additionalProperties
  • items
  • maxItems
  • minItems
  • uniqueItems

integer (Number uses the same properties so if you need number, set your type explicitly)

  • exclusiveMaximum
  • exclusiveMinimum
  • maximum
  • minimum
  • multipleOf

object

  • additionalItems
  • dependencies
  • maxProperties
  • minProperties
  • patternProperties
  • properties
  • required

string

  • maxLength
  • minLength
  • pattern

Automation: grunt plugin

Use grunt-jsonschema-faker to automate running json-schema-faker against your JSON schemas.

Great, Why?

Actually, I've found some projects or services:

Many of they are incomplete (?), so I decided to code this library.

Contribution

Any contribution is well received, please see contribution guide.

json-schema-faker's People

Contributors

ducin avatar pateketrueke avatar raynos avatar whitlockjc avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.