Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 13, 2021 07:07 am GMT

Create Fake Data Easily Using JavaScript

Ever need to populate a table or generate some data to see what your GUI looks like when its in use? Need to test the performance of your application under load? Have to do a demo but you dont have any legitimate data to do the demo as its pre-release?

Usually in this scenario, a programmer has one of two options:

  1. Manually input the data by hand
  2. Code your own seeding application that does it all for you

Neither of these scenarios are ideal. Manually inputting data by hand can take time, a lot of time. Coding your own seeding application is not as easy as youd think, you need to understand the process of generating random text, dummy images, random dates, names, emails, etc.

What is Faker.js

Introducing Faker.js a brilliant solution to help you generate data and seed your application. Faker.js can be used either in the browser, or using node.js. All the problems and quirks with generating random data some listed above have been thought of and solved in Faker, so we dont need to spend any more time reinventing the wheel.

Generating User Data

The most common scenario I can think of and was required at work just a couple weeks ago is generating User data. Lets create a dummy node app that has a GET/ users request thatll return a list of generated users. For the sake of this blog Ill leave out the complexities of pagination, Ill just return an array of 100 users.

const express = require("express");const app = express();app.listen(3000, () => { console.log("Server running on port 3000");});app.get("/users", (req, res, next) => {    res.json([        {            "name": "Douglas Adams",            "email": "[email protected]",            "postcode": "pe22 22a",            "phoneNumber": "07428233312",            "city": "London",            "country": "England",            "favouriteQuote": "The answer is 42"        }    ]);});

So if we call the endpoint GET http://localhost:3000/users:

Response:

[    {        "name": "Douglas Adams",        "email": "[email protected]",        "postcode": "pe22 22a",        "phoneNumber": "07428233312",        "city": "London",        "country": "England",        "favouriteQuote": "The answer is 42"    }]

This is the basic format of the data we want to generate. Lets make use of Faker to do this for us.

Faker is super simple, all you need to do is scan their README.md for a good understanding of how theyve structured it. Basically, theres a list of objects that you can reference and each of those objects have methods that you can call. For example, theres an address which has methods such as:

zipCode()zipCodeByState()city()cityPrefix()citySuffix()// and a load more

So to get a random zip code Id simply need to make the following call:

faker.address.zipCode()

Lets incorporate this into our code:

npm install faker

const express = require("express");const faker = require('faker');const app = express();app.listen(3000, () => { console.log("Server running on port 3000");});app.get("/users", (req, res, next) => {    res.json([        {            "name": faker.name.findName(),            "email": faker.internet.email(),            "postCode": faker.address.zipCode(),            "city": faker.address.cityName(),            "country": faker.address.country(),            "phoneNumber": faker.phone.phoneNumber(),            "favouriteQuote": faker.lorem.sentence()        }    ]);});

So now when I make the request, the response it returns is:

[    {        "name": "Darnell Marquardt",        "email": "[email protected]",        "postCode": "56653",        "city": "Mount Vernon",        "country": "Paraguay",        "phoneNumber": "987-214-5854 x674",        "favouriteQuote": "Harum veritatis est dolore amet nam debitis."    }]

And if I run it again Ill get a different result:

[    {        "name": "Victoria Kerluke V",        "email": "[email protected]",        "postCode": "15058",        "city": "Kendall",        "country": "Serbia",        "phoneNumber": "751.325.8108 x50407",        "favouriteQuote": "Deserunt rerum maiores."    }]

Next, lets update the code so it actually returns an array of 100 users:

app.get("/users", (req, res, next) => {    res.json(getUsers());});function getUsers() {    let users = [];    for (let i = 0; i < 100; i++) {        users.push({            "name": faker.name.findName(),            "email": faker.internet.email(),            "postCode": faker.address.zipCode(),            "city": faker.address.cityName(),            "country": faker.address.country(),            "phoneNumber": faker.phone.phoneNumber(),            "favouriteQuote": faker.lorem.sentence()        })    }    return users;}

Response:

[    {        "name": "Sandra Schaefer",        "email": "[email protected]",        "postCode": "65665",        "city": "Palm Harbor",        "country": "Slovakia (Slovak Republic)",        "phoneNumber": "379-607-0449",        "favouriteQuote": "Qui consectetur repellendus commodi."    },    {        "name": "Mark Veum",        "email": "[email protected]",        "postCode": "89859",        "city": "Montebello",        "country": "Myanmar",        "phoneNumber": "779.494.2905 x0531",        "favouriteQuote": "Corrupti assumenda enim alias suscipit maxime molestiae quis laboriosam."    },   // you get the idea..

Using a seed

Let's imagine a scenario. You're doing a demonstration of the new users page, you click to open up the page, a GET users request is made, random users are returned. You spend a little time on the page, people become accustomed to the names of the users in the table. Then you come off the page to change some config. You go back to the page, a GET users request is made and different random users are returned, "What happened to Sandra" someone asks.

The thing that I love most about Faker, is that you can use a randomness seed meaning you can get consistent results every time you make a call. This is something that you most likely wouldn't implement if you were creating your own random data, well at least, I wouldn't.

Let's use a seed in our request:

app.get("/users", (req, res, next) => {    faker.seed(123);    res.json(getUsers());});

Now every time I make a request the same data gets returned:

Going to the users page for the first time:

[    {        "name": "Clara Keebler",        "email": "[email protected]",        "postCode": "79465",        "city": "Lancaster",        "country": "Burundi",        "phoneNumber": "536.734.2063",        "favouriteQuote": "Id harum sit odio quia vitae provident."    },    {        "name": "Kristin Nicolas",        "email": "[email protected]",        "postCode": "74363",        "city": "Guaynabo",        "country": "Czech Republic",        "phoneNumber": "496-807-4041",        "favouriteQuote": "Sequi molestiae beatae enim necessitatibus molestiae."    },   // etc

Coming back to the users page:

[    {        "name": "Clara Keebler",        "email": "[email protected]",        "postCode": "79465",        "city": "Lancaster",        "country": "Burundi",        "phoneNumber": "536.734.2063",        "favouriteQuote": "Id harum sit odio quia vitae provident."    },    {        "name": "Kristin Nicolas",        "email": "[email protected]",        "postCode": "74363",        "city": "Guaynabo",        "country": "Czech Republic",        "phoneNumber": "496-807-4041",        "favouriteQuote": "Sequi molestiae beatae enim necessitatibus molestiae."    },   // etc

Summary

Generating random data is something all programmers will have to do at some point. With Faker.js it's an easier ride. Simply npm install for a node app or add it to your frontend solution. Need some data but don't have a backend to supply the data yet, then use faker.js.

I hope you've enjoyed this blog, if you do by some miracle enjoy my blabbering then head over to my blogging site at codeheir.com where I write weekly blogs about whatever in the world of programming has my attention!


Original Link: https://dev.to/lukegarrigan/create-fake-data-easily-using-javascript-4mkj

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To