How to use the json-schema-faker.extend function in json-schema-faker

To help you get started, weā€™ve selected a few json-schema-faker examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github json-schema-faker / json-schema-server / lib / server.js View on Github external
configureJSF: function configureJSF() {
    // TODO: check only if diff/checksum changes on each request,
    // if changed just reload the entire module before faking anything
    try {
      this.log('Configuring json-schema-faker');

      if (this.params.formats) {
        jsf.format(require(this.params.formats));
      }

      jsf.extend('faker', () => require('faker'));
      jsf.extend('chance', () => new (require('chance'))());
    } catch (e) {
      return this.callback(e);
    }
  },
github json-schema-faker / json-schema-server / lib / server.js View on Github external
configureJSF: function configureJSF() {
    // TODO: check only if diff/checksum changes on each request,
    // if changed just reload the entire module before faking anything
    try {
      this.log('Configuring json-schema-faker');

      if (this.params.formats) {
        jsf.format(require(this.params.formats));
      }

      jsf.extend('faker', () => require('faker'));
      jsf.extend('chance', () => new (require('chance'))());
    } catch (e) {
      return this.callback(e);
    }
  },
github EricHenry / swagger-data-gen / src / SwaggerDataGen.ts View on Github external
import * as SwaggerParser from 'swagger-parser';
import * as jsf from 'json-schema-faker';
import * as faker from 'faker';
import * as formatters from './formatters';
import * as middleware from './middleware';
import { requireProps, fakerDate, fakerMatcher } from './middleware';
import { binary, byte, fullDate, password } from './formatters';
import { configure, generateData } from './utils';
import { Formatter, Middleware, BuildOptions } from './types';
import { Spec as Swagger } from 'swagger-schema-official';

jsf.extend('faker', () => faker);

  // if this is set, it will override all other middleware config values. true will enable all, false will disable all
const DEFAULT_CONFIG_FORMATTER = { default: true };
const DEFAULT_CONFIG_MIDDLEWARE = { default: true };

export const CORE_MIDDLEWARE: Middleware[] = [requireProps, fakerMatcher, fakerDate];
export const CORE_FORMATTERS: Formatter[] = [binary, byte, fullDate, password];

/**
 * Bundle the API,
 * add / remove middleware and formatters based on config.
 * apply middleware and formatters
 * dereference the Swagger / OpenAPI file / object
 * save the paresed file as an object property on the current instance of the SwaggerDataGenerator Class
 *
 * @param {string} [swaggerSchema]   - the path to the Swagger file
github stoplightio / prism / packages / http / src / mocker / generator / JSONSchema.ts View on Github external
import * as faker from 'faker';
import { cloneDeep } from 'lodash';
import { JSONSchema } from '../../types';

// @ts-ignore
import * as jsf from 'json-schema-faker';
// @ts-ignore
import * as sampler from 'openapi-sampler';
import { Either, tryCatch, toError } from 'fp-ts/lib/Either';

jsf.extend('faker', () => faker);

jsf.option({
  failOnInvalidTypes: false,
  failOnInvalidFormat: false,
  alwaysFakeOptionals: true,
  optionalsProbability: 1,
  fixedProbabilities: true,
  ignoreMissingRefs: true,
  maxItems: 20,
  maxLength: 100,
});

export function generate(source: JSONSchema): Either {
  return tryCatch(() => jsf.generate(cloneDeep(source)), toError);
}
github unmock / unmock-js / packages / unmock-core / src / generator.ts View on Github external
const generateMockFromTemplate = ({
  rng,
  statusCode,
  headerSchema,
  bodySchema,
}: {
  rng: () => number;
  statusCode: number;
  headerSchema?: any;
  bodySchema?: any;
}): ISerializedResponse => {
  jsf.extend("faker", () => require("faker"));
  jsf.option("optionalsProbability", runnerConfiguration.optionalsProbability);
  // When optionalsProbability is set to 100%, generate exactly 100% of all optionals.
  // otherwise, generate up to optionalsProbability% of optionals
  jsf.option(
    "fixedProbabilities",
    runnerConfiguration.optionalsProbability === 1,
  );
  // disables this temporarily as it messes with user-defined min items
  // jsf.option("minItems", runnerConfiguration.minItems);
  // jsf.option("minLength", runnerConfiguration.minItems);
  jsf.option("useDefaultValue", false);
  jsf.option("random", rng);
  const bodyAsJson = bodySchema ? jsf.generate(bodySchema) : undefined;
  const body = bodyAsJson ? JSON.stringify(bodyAsJson) : undefined;
  jsf.option("useDefaultValue", true);
  const resHeaders = headerSchema ? jsf.generate(headerSchema) : undefined;
github YMFE / yapi / server / utils / commons.js View on Github external
const userModel = require('../models/user.js');
const followModel = require('../models/follow.js');
const json5 = require('json5');
const _ = require('underscore');
const Ajv = require('ajv');
const Mock = require('mockjs');



const ejs = require('easy-json-schema');

const jsf = require('json-schema-faker');
const { schemaValidator } = require('../../common/utils');
const http = require('http');

jsf.extend ('mock', function () {
  return {
    mock: function (xx) {
      return Mock.mock (xx);
    }
  };
});

const defaultOptions = {
  failOnInvalidTypes: false,
  failOnInvalidFormat: false
};

// formats.forEach(item => {
//   item = item.name;
//   jsf.format(item, () => {
//     if (item === 'mobile') {
github EricHenry / swagger-data-gen / src / sdg.js View on Github external
const SwaggerParser = require('swagger-parser');
const jsf = require('json-schema-faker');
const generators = require('./formatters');
const middleware = require('./middleware');
const { configure, generateMock } = require('./utils');

jsf.extend('faker', () => require('faker'));

const DEFAULT_RUN_CONFIG = {
  formatters: {
    binary: true,    // optional - true will apply the formatter
    byte: true,      // optional - true will apply the formatter
    fullDate: true,  // optional - true will apply the formatter
    password: true,  // optional - true will apply the formatter
    all: true        // optional - if this is set, it will override all other formatter config values. true will enable all, false will disable all
  },
  middleware: {
    fakerMatcher: true,  // optional - true will apply the middleware
    fakerDate: true,     // optional - true will apply the middleware
    requireProps: true,  // optional - true will apply the middleware
    all: true            // optional - if this is set, it will override all other middleware config values. true will enable all, false will disable all
  }
};
github ali322 / nva / packages / nva-server / lib / mock.js View on Github external
module.exports = (conf, logText) => {
  const app = connect()

  jsf.extend('faker', function() {
    return require('faker/locale/en_US')
  })
  let mocks = {}
  let allRules = []
  let watcher
  if (isString(conf) && conf) {
    conf.split(',').forEach(v => {
      let files = glob.sync(v)
      files.forEach(file => {
        let rules = []
        try {
          rules = require(resolve(file))
        } catch (e) {
          console.log(prettyError(e))
          mocks[file] = []
          return false
github whj1995 / ts-faker / src / index.ts View on Github external
export default async function fake(files: string[], settings: ISettings = { locale: 'en' }, transform = (_symboyName: string, jsonSchema: any) => jsonSchema) {
  const locale = settings.locale || 'en';
  jsf.extend('faker', () => require(`faker/locale/${locale}`));

  const program = tjs.getProgramFromFiles(files, { lib: ['esnext'] });
  const validationKeywords = settings.validationKeywords ? ['faker', ...settings.validationKeywords] : ['faker'];
  const generator = tjs.buildGenerator(program, { ...settings, validationKeywords, required: true, include: files }, files)!;
  const userSymbols = generator.getUserSymbols();
  const datas: any = {};
  const fakeDatas = await Promise.all(
    userSymbols.map((sym) => jsf.resolve(
      transform(sym, generator.getSchemaForSymbol(sym)))
    )
  );
  for (let i = 0; i < fakeDatas.length; ++i) {
    datas[userSymbols[i]] = fakeDatas[i];
  }
  return datas;
}
github MoonMail / MoonMail / lists-microservice / scripts / deploy-docs.js View on Github external
#!/usr/bin/env node

const program = require('commander');
const aws = require('aws-sdk');
const fs = require('fs');
const spectacle = require('spectacle-docs');
const jsf = require('json-schema-faker');
const Promise = require('bluebird');
const schemaTraverse = require('json-schema-traverse');

jsf.format('cuid', require('cuid'));
jsf.option({ alwaysFakeOptionals: true });
jsf.extend('chance', () => {
  const Chance = require('chance');
  const chance = new Chance();
  chance.mixin({
    metadata: () => ({
      name: chance.first(),
      surname: chance.last(),
      countryCode: chance.country(),
      foo: 'bar'
    })
  });
  return chance;
});

program
  .usage('[options]')
  .description('Deploy API Gateway documentation')