Building an e-Commerce website with Node – Part 31 – Integrating Faker API in Node.js

Using Faker we will be able to store the product data in the database without actually creating a product one by one.

First let’s create a new folder under the MyEshop folder and name it api. This folder will store most of the API URL. If the route is responding with a JSON data you will want to put it in a different file, which is api.js file.

Under the api folder let’s create the api.js file. In the api.js file type the following code.

var router = require('express').Router();
var async = require('async');
var faker = require('faker');
var Category = require('../models/category');
var Product = require('../models/product');

router.get('/:name', function(req, res, next) {
    async.waterfall([
      function(callback) {
        Category.findOne({ name: req.params.name }, function(err, category) {
          if (err) return next(err);
          callback(null, category);
        });
      },

      function(category, callback) {
        for (var i = 0; i < 30; i++) {
          var product = new Product();
          product.category = category._id;
          product.name = faker.commerce.productName();
          product.price = faker.commerce.price();
          product.image = faker.image.image();

          product.save();
        }
      }
    ]);
    res.json({ message: 'Success' });
});

module.exports = router;

We required faker and async libraries but they are not installed. We are going to install them via the terminal by running the command npm install faker async -- save.

First, we search the name of the category, based on the name we type in. Next is just a normal function with the parameters response, request, and a callback, and then we do the async.

In the async there are two functions. First function is with index 0 and the second function is with index 1. First function search for the requested category and when it finds it the category is passed in a callback and it goes to the next function.

The code in the second function is self explanatory. It loops thirty times and it creates a new product each time. Faker will assign a name, a price, and an image to each created product. You can learn more about Faker at this link https://github.com/marak/Faker.js/.

Now, open server.js file and add the following two lines of code.

var apiRoutes = require('./api/api');

and

app.use('/api', apiRoutes);

Now, you can start the server. When I did I got an error “Module mongoosastic not found”. If you get something similar then go ahead and install it via the terminal by running the command npm install mongoosastic --save.

You can also check the mLab database to see the thirty products created by Faker.

Leave a Reply