47

Laravel's factory method but for JavaScript

 5 years ago
source link: https://www.tuicool.com/articles/mMrAFjy
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

factory

Generate lots of mock data with ease using Marak/faker.js .

Installation

$ npm install --save-dev @grahamsutton/factory

Usage

Function Signature

factory(numRecords: Number, callback: Function): Array

NOTE: numRecords must be an integer or an error will be thrown.

Example

const factory = require('@grahamsutton/factory')

let users = factory(2, (faker, index) => {
  return {
    "id": index + 1,
    "name": faker.name.firstName(),
    "email": faker.internet.email(),
    "departments": factory (4, () => {
      return faker.commerce.department()
    }),
    "addresses": factory(2, () => {
      return {
        "street": faker.address.streetAddress(),
        "city": faker.address.city(),
        "state": faker.address.state()
      }
    })
  }
})

This would return an array with the following structure:

[
  {
    "id": 1,
    "name": "Mike",
    "email": "[email protected]",
    "departments": [
      "Automotive", "Grocery", "Sports", "Electronics"
    ],
    "addresses": [
      {
        "street": "665 Alexander Corner",
        "city": "Doylehaven",
        "state": "Florida"
      },
      {
        "street": "479 Adrain Tracer",
        "city": "Dibbertchester",
        "state": "New York"
      }
    ]
  },
  {
    "id": 2,
    "name": "Sam",
    "email": "[email protected]",
    "departments": [
      "Sports", "Beauty", "Automotive", "Electronics"
    ],
    "addresses": [
      {
        "street": "12780 Juston Neck",
        "city": "Walterville",
        "state": "Alabama"
      },
      {
        "street": "579 Rashad Loop",
        "city": "South Tristinmouth",
        "state": "Idaho"
      }
    ]
  }
]

Contributing

See the CONTRIBUTING.md file for instructions on contributing. Any contributers are welcome!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK