Search This Blog

2018/09/07

Javascript Promise & Async/await

What is promise ?
    Promise is an object that represent result of  asynchronous operation in future.Promise can be in one of following state

        1) pending - The initial state of a promise.
        2) resolved - The state of a promise representing a successful operation.
        3) rejected - The state of a promise representing a failed operation.

    Once a promise is resolved or rejected it remain so it can't change it state further.In sense it is immutable.

Initial Javascript do not have native promises library though there were third party implementation like Deferred,Q,Asyc.js or bluebird.
ES6 brought a Promises natively to javascript.

Only the function responsible for creating the promise will have knowledge of the promise status, or access to resolve or reject.
The ES6 promise constructor takes a function. That function takes two parameters, resolve(), and reject().
You can resolve() or reject() with values, which will be passed to the callback functions attached with .then().
e.g.
     assume we want to get IP address of client through REST API.'request-promise' is promisified version of 'request' library.
promise provide alternative to callback.

    var Request = require("request");
    var RequestPromise = require('request-promise');

    var getPublicIp = function () {
        return new Promise(function (resolve, reject) {
        RequestPromise('http://httpbin.org/ip')
            .then(function (htmlString) {
                resolve(JSON.parse(htmlString))
            })
            .catch(function (err) {
                reject(err)
            });
        }
        );
    }

we can call this function as

    getPublicIp()
        .then(function (fulfilled) {
        console.log('Public Ip Address:' + fulfilled.origin)
        })
        .catch(function (error) {
        console.log("Error:" + error);
        })

or using async/await as

    async function getPublicIpAsyc() {
        try {
        var result = await getPublicIp();
        console.log("Async/Await:" + JSON.stringify(result))
        } catch (err) {
        console.log("Async/Await:" + err)
        }

    }

    getPublicIpAsyc();

Here await can be used only inside function which is defined as async.Async/await is new feature that await ask calling function to wait till get response of statement marked with await.
async/await let us to handle exception in single try catch unlike promise where we have to chain catch block after then block.

2018/09/06

CRUD opeation using Mongoose & Express.js

Mongoose is an ORM for mongodb in node.js.
It provides validation of property like field is required,max length & min length of text field & many more.

we will create an express application that does CRUD operation on mongo using mongoose.


First lets create an express app

    express --view=ejs myapp

add models folder.Into models folder add user.js with following code

    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;

    mongoose.connect('mongodb://localhost/palbum');

    // create a schema
    var userSchema = new Schema({
        firstname: String,
        lastname: String,
        username: { type: String, required: true, unique: true },
        password: { type: String, required: true },
        admin: { type: Boolean, default: false },
        location: { type: String, minlength: 5, maxlength: 15 },
        meta: {
        age: { type: Number, min: 5 },
        website: String
        },
        created_at: { type: Date, default: Date.now },
        updated_at: { type: Date, default: Date.now }
    });

    //instance method
    userSchema.methods.dudify = function () {
        this.name = this.name + '-dude';
        return this.name;
    };

    //static method
    userSchema.statics.findByLocation = function(location, cb) {
        return this.find({ location: new RegExp(location, 'i') }, cb);
    };

    // we need to create a model using it
    var User = mongoose.model('User', userSchema);

    // make this available to our users in our Node applications
    module.exports = {
       "User": User,
       "UserSchema":userSchema
    }

In user schema validation has been put in place over username to ensure uniqueness of username across records. "location" has been asssigned maxlength & minlength validation defaukt value has been set on created_at & updated_at.

In mongoose we can add instance method & static method."findByLocation" is static method while "dudify" is instance method.for using "dudify" we need instance of User unlike "findByLocation".

update route/users.js as follows

    var express = require('express');
    var router = express.Router();
    var User = require('../models/user').User;
    var userSchema = require('../models/user').userSchema;
    var mongoose = require('mongoose');

    /* GET users listing. */
    router.get('/', function (req, res, next) {
      res.send('respond with a resource');
    });


    router.post('/add', function (req, res, next) {
      // create a new user called chris
      var postUser = new User({
        firstname: req.body.firstname,
        lastname: req.body.lastname,
        location: req.body.location,
        meta: {
          age: req.body.age,
          website: req.body.website
        },
        username: req.body.username,
        password: req.body.password,
      });

      //dudify
      postUser.dudify(function (err, name) {
        if (err) throw err;
        console.log('Your new name is ' + name);
      });

      postUser.save(function (err) {
        if (err) throw err;
        console.log('User saved successfully!');
        res.send('User saved successfully!');
      });


    });

    router.post('/location', function (req, res, next) {
      var User = mongoose.model('User', userSchema);
      User.findByLocation(req.body.location, function (err, users) {
        console.log(users);
        res.json(users);
      });
    });

    router.get('/getAll', function (req, res, next) {
      // get all the users
      User.find({}, function (err, users) {
        if (err) throw err;

        // object of all the users
        console.log(users);
        res.json(users);
      });
    });

    router.get('/get/:username', function (req, res, next) {
      User.find({ username: req.params.username }, function (err, user) {
        if (err) throw err;

        // object of the user
        console.log(user);
        res.json(user);
      });
    });

    router.delete('/findthenremove/:username', function (req, res, next) {
      console.log("username" + req.params.username);
      User.find({ username: req.params.username }, function (err, user) {
        if (err) throw err;

        console.log(JSON.stringify(user));

        if (user == undefined || user == null) {
          res.json({
        "success": 0,
        "data": {},
        "message": "user not found!"
          });
        } else {

          // delete him
          User.deleteOne({ username:  req.params.username }, function (err) {
        if (err) return handleError(err);

        console.log('User successfully deleted!');
        res.json({
          "success": 1,
          "data": user,
          "message": "user removed!"
        });
          });

        }
      });
    });


    router.delete('/findandremove/:username', function (req, res, next) {
      console.log("username" + req.params.username);

      User.findOneAndRemove({ username: req.params.username }, function (err) {
        if (err) throw err;

        // we have deleted the user
        console.log('User deleted!');
        res.json('User deleted!')
      });
    });

    router.put('/update/:username', function (req, res, next) {
      User.updateOne({ username: req.params.username }, { password: req.body.password}, function(err, resp) {
        res.json("user password updated!");
      });
    });

    module.exports = router;

we have following endpoints

1) adding new user:
    Endpoint:http://localhost:3000/users/user
    Method:http post
    Header:Content-Type:application/json
    sample Payload:
    {
        "firstname": "Chris",
        "lastname":"harris",
        "username": "oneoneone",
        "password": "password",
        "location":"puneeee",
        "age":36,
        "website":"msdotnetbuddy.blogspot.in"
    }
   response:User saved successfully!

2)find by location:list all record with location mumbai.

    Endpoint: http://localhost:3000/users/location
    Method:post
    Header:Content-Type:application/json
    Payload:
    {
        "location":"mumbai"
    }
    Response:
    [
        {
        "meta": {
            "age": 36,
            "website": "msdotnetbuddy.blogspot.in"
        },
        "admin": false,
        "_id": "5b90e1e549999d1d073d79ca",
        "firstname": "Chris",
        "lastname": "harris",
        "location": "mumbai",
        "username": "one",
        "password": "password",
        "created_at": "2018-09-06T08:14:29.295Z",
        "updated_at": "2018-09-06T08:14:29.295Z",
        "__v": 0
        }
    ]
3) List all Records:
       Endpoint:http://localhost:3000/users/getAll
       method:get
       response:
        [
            {
            "admin": false,
            "created_at": "2018-09-06T12:02:39.372Z",
            "updated_at": "2018-09-06T12:02:39.372Z",
            "_id": "5b90dfab631d041a2aa22b47",
            "name": "Chris-dude",
            "username": "sevilayha",
            "password": "password",
            "__v": 0
            },
            {
            "admin": false,
            "_id": "5b90e0ce168db71c5bd4284a",
            "username": "chris",
            "password": "password",
            "created_at": "2018-09-06T08:09:50.942Z",
            "updated_at": "2018-09-06T08:09:50.942Z",
            "__v": 0
            },
            {
            "meta": {
                "age": 36,
                "website": "msdotnetbuddy.blogspot.in"
            },
            "admin": false,
            "_id": "5b90e1e549999d1d073d79ca",
            "firstname": "Chris",
            "lastname": "harris",
            "location": "mumbai",
            "username": "one",
            "password": "password",
            "created_at": "2018-09-06T08:14:29.295Z",
            "updated_at": "2018-09-06T08:14:29.295Z",
            "__v": 0
            },
            {
            "meta": {
                "age": 36,
                "website": "msdotnetbuddy.blogspot.in"
            },
            "admin": false,
            "_id": "5b90e6a851b57b2056e18210",
            "firstname": "Chris",
            "lastname": "harris",
            "location": "puneeee",
            "username": "oneoneone",
            "password": "password",
            "created_at": "2018-09-06T08:34:48.451Z",
            "updated_at": "2018-09-06T08:34:48.451Z",
            "__v": 0
            }
        ]
4)find single record by username
          Endpoint:http://localhost:3000/users/get/one
          Method:Get
      response:
        [
            {
            "meta": {
                "age": 36,
                "website": "msdotnetbuddy.blogspot.in"
            },
            "admin": false,
            "_id": "5b90e1e549999d1d073d79ca",
            "firstname": "Chris",
            "lastname": "harris",
            "location": "mumbai",
            "username": "one",
            "password": "password",
            "created_at": "2018-09-06T08:14:29.295Z",
            "updated_at": "2018-09-06T08:14:29.295Z",
            "__v": 0
            }
        ]
5)Delete:find & remove and coupled together rather than in two stages
    Endpoint:http://localhost:3000/users/findandremove/sevilayha
        Method:http/delete
    response:"User deleted!"

6) Delete:find & remove are decoupled
      Endpoint:http://localhost:3000/users/findthenremove/chris
      method:http/delete
      response:
    {
        "success": 1,
        "data": [
        {
            "admin": false,
            "_id": "5b90e0ce168db71c5bd4284a",
            "username": "chris",
            "password": "password",
            "created_at": "2018-09-06T08:09:50.942Z",
            "updated_at": "2018-09-06T08:09:50.942Z",
            "__v": 0
        }
        ],
        "message": "user removed!"
    }
7)Update:it updates password to new value.
    Endpoint:http://localhost:3000/users/update/oneoneone
    Header:Content-Type:application/json
    Payload:
        {
        "password":"newpassword"
        }
    Response:"user updated!"

Code of this article can be viewed at https://github.com/gitsangramdesai/mongoose-express-rest