📜 ⬆️ ⬇️

Generating fake data for your javascript application using faker

In order to demonstrate the work of the application, we often have to force it to work with fictitious data, because it is not necessary that the headers are empty and the tables are only lined but not filled.

As a rule, when creating an application, we don’t really worry about exactly what data it will ultimately work with, we just invent some example that is enough to continue working on logic, and, in fact, we continue work on logic.

Fortunately, Marak has created a neat tool that allows us to generate fake data on the fly: Faker .

Let's start with a small example.


Suppose we need to create a user on the fly. We want him to have a name, mail, address, biography, and even an avatar.
')
What allows us to do Faker:

var user = { name: faker.name.findName(), email: faker.internet.email(), address: faker.address.streetAddress(), bio: faker.lorem.sentence(), image: faker.image.avatar() }; 

Everything. Now we have a full-fledged user, in the image of an object, which has all the desired properties:

 { "name": "Adaline Carroll", "email": "Albina.Ledner@gmail.com", "address": "545 Fritsch Locks", "bio": "dolorem officiis doloribus ut", "image": "https://s3.amazonaws.com/uifaces/faces/twitter/joelhelin/128.jpg" } 

Now we can do with our user anything, in any part of the program, without having to deal with the database, which would have to be populated manually. Then I will tell you about some interesting features of Faker.

Using Faker


You can work with Faker both in the browser and on the server using Node.
Following the documentation we will deal with how to configure and install it.

Connect to page


 <!-- LOAD FAKER --> <script src="faker.js"> <script> var name = faker.name.findName(); var randomEmail = faker.internet.email(); </script> 


Jobs at Node


  var faker = require('faker'); var name = faker.name.findName(); var randomEmail = faker.internet.email(); 

That's all. Let's see what else we can work with.

Faker data


The list of data that Faker can generate for us is long enough. Here is the main one:

Each of the items has many sub-items and settings. For example:

Each property can be accessed using the function:
  // Chris var firstName = faker.name.firstName(); // Sevilleja var lastName = faker.name.lastName(); // Chris Sevilleja var findName = faker.name.findName(); // Mr. var prefix = faker.name.prefix(); // PhD var suffix = faker.name.suffix(); 

A full list of data descriptions that Faker allows you to work with can be found here .

"Helpers"


Also for many categories of data, Faker provides a set of “helpers”, which are designed to further simplify the work. Instead of extracting content from one field, and then taking on another, “helpers” allow you to work with ready, pooled data sets.
I will give a few examples.

fakers.helpers.contextualCard ()


Ready set of user data, which includes first name, last name, mail, address and avatar:
 { "name": "Kaleigh", "username": "Kaleigh60", "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/mbilderbach/128.jpg", "email": "Kaleigh6047@gmail.com", "dob": "1961-08-07T02:37:45.068Z", "phone": "113.601.0680", "address": { "street": "Myah Course", "suite": "Apt. 657", "city": "Boyerberg", "zipcode": "66413-8920", "geo": { "lat": "-44.6203", "lng": "16.7454" } }, "website": "megane.biz", "company": { "name": "Little-Reinger", "catchPhrase": "Enhanced regional emulation", "bs": "interactive generate bandwidth" } } 


fakers.helpers.userCard ()


The abbreviated data set, but which includes the avatar:
 { "name": "George Kohler", "username": "Emilio_Grady49", "email": "Aurore_Wintheiser90@gmail.com", "address": { "street": "Corwin Cove", "suite": "Suite 550", "city": "New Myah", "zipcode": "57817", "geo": { "lat": "-3.4045", "lng": "-16.7806" } }, "phone": "1-806-338-0724 x844", "website": "katheryn.net", "company": { "name": "Purdy, Lesch and Jacobi", "catchPhrase": "Programmable incremental frame", "bs": "24/365 optimize initiatives" } } 


fakers.helpers.createTransaction ()


 { "amount": "757.24", "date": "2012-02-02T08:00:00.000Z", "business": "Bahringer Group", "name": "Home Loan Account 5279", "type": "deposit", "account": "63843216" } 


faker.helpers.createCard ()


A complete set of user data, including posts, is needed to simulate blog entries:
 { "name": "Fern Ritchie", "username": "Vladimir.Feest", "email": "Llewellyn_Robel@gmail.com", "address": { "streetA": "Ratke Street", "streetB": "431 Terry Prairie", "streetC": "027 Tyler Plaza Apt. 166", "streetD": "Apt. 095", "city": "Crooksstad", "state": "New Hampshire", "country": "Ukraine", "zipcode": "53303", "geo": { "lat": "-5.9355", "lng": "20.5942" } }, "phone": "477-849-4756 x71564", "website": "emile.org", "company": { "name": "Stehr Inc", "catchPhrase": "Universal 6th generation contingency", "bs": "granular whiteboard bandwidth" }, "posts": [{ "words": ["voluptatem", "quia", "ipsam"], "sentence": "maxime et nemo et sed", "sentences": "blanditiis sint molestiae facilis\net molestiae velit consequatur sit aut iure nihil\neaque quo voluptatibus", "paragraph": "reiciendis exercitationem assumenda provident odio\nasperiores fugit officia\nperferendis exercitationem a\nnam et ea\na ex autem ducimus\nsint tenetur officia ratione nesciunt impedit qui" }, { "words": ["voluptatem", "fugiat", "laborum"], "sentence": "quis vel consequatur placeat eum voluptas laboriosam", "sentences": "natus ut assumenda esse rerum repudiandae\ntempore excepturi nemo et velit inventore minus nihil officiis\nexcepturi corrupti enim explicabo quaerat", "paragraph": "sint eum tenetur id occaecati\nitaque veritatis aperiam libero quibusdam repudiandae explicabo accusamus rerum inventore\net placeat enim\ndolor sit dolores nulla doloribus" }, { "words": ["illum", "quia", "voluptas"], "sentence": "libero eos quia velit qui sint aut", "sentences": "eligendi esse blanditiis magni perferendis cumque quibusdam qui iste vitae\naliquam odio aut quaerat\nveritatis consequatur qui consequuntur", "paragraph": "qui facere ex et consequatur\nut iusto maxime quia deleniti sint aut\nut inventore magni ipsum necessitatibus et numquam qui consectetur aperiam\nnam non quisquam tempore corporis adipisci nobis rem\nqui doloribus inventore itaque est corrupti modi vero quidem quaerat" }], "accountHistory": [{ "amount": "435.13", "date": "2012-02-02T08:00:00.000Z", "business": "Dare Inc", "name": "Home Loan Account 4225", "type": "payment", "account": "69883581" }, { "amount": "993.77", "date": "2012-02-02T08:00:00.000Z", "business": "Yundt, VonRueden and Marks", "name": "Credit Card Account 2737", "type": "withdrawal", "account": "32957725" }, { "amount": "844.46", "date": "2012-02-02T08:00:00.000Z", "business": "Sipes-Boyer", "name": "Investment Account 5882", "type": "deposit", "account": "50708763" }] } 


Using the Node API Template


We can quickly create a Node API that will return fake data. In this example, the end result of working with the API will be the return of user data:
 app.get('/api/user', function(req, res) { res.json({ name: faker.name.findName(), email: faker.internet.email(), address: faker.address.streetAddress(), bio: faker.lorem.sentence(), image: faker.image.avatar() }; }); 

After the server has been started, the result of the API will be displayed by Postman; as we see, this is JSON data: image

findings


I hope that Faker will simplify the creation of applications to some developers. This package allows you to easily generate data and organize work through the API. Also recommending a visit to the official site of the project, there you will find many interesting things and be able to estimate the amount of data that Faker allows to manipulate.

Source: https://habr.com/ru/post/248999/


All Articles