Posted by: Zeeshan Amjad | September 2, 2018

Writing Webservice with node.js and express


Node js is very popular and easy to use technology to write server side code in JavaScript language. with the additin of express js library it would be very easy to write not only the web service, but also middle ware for any full stack application. Node js and express are very popualar to all Java Script full stake platform such as MEAN (MongoDB, Express, Angular, Node) and MERN (MongoDB, Express, React, Node). Application written using MEAN and MERN stack are not only cross platform, but also written in one language i.e. Java Script, therefore it is comparatively easy to build the full stack application in one language.

The first step to write application is to install node which is available in all platform. https://nodejs.org You can check if you have install nodejs on your computer or not by running “node –v”.

Once node js is isntall then create a new application by runing the “npm init” command. It will ask some questions and if selected all default options will create a file package.json

{
  "name": "experiment",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

Then install the express library by runining the following command “npm install express –save”. It will change the package.json file and added the “dependencies” section and it will look like this.

{
  "name": "experiment",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.3"
  }
}

Here the ^ sign before the version of express shows that it will get the latest major version of express if available.

The complete code to write the simple web service.

var express = require('express')

var port = 5000

var app = express()

app.get('/', (req, res) => {

res.send('Hello world from node')

})

app.listen(port, () => {

console.log(`listening on port ${port}`)

})

Save this file as index.js (because in package.json the file name is index.js) We can run this application by runing “node index.js” in the command prompt.If you open localhost:5000 in the browser you will see “Hello world from node”. Now let’s make something useful. If we want to pass some query paramter to the web service url we can get it with req.query.

Let’s make a simple application that perform some financial calculationss. Before that let’s make a small change in the package.json file. Add the following line in package.json under the script section and it will become like this.

"scripts": {

"start": "node index.js",

"test": "echo \"Error: no test specified\" && exit 1"

},

The advantage of this is now we can run the application by just running “npm start” command.

Here is a compelete code of some basic financial web services.

var express = require('express')

var port = 5000
var app = express()

app.get('/', (req, res) => {    

    var x = parseFloat(req.query.x);
    var y = parseFloat(req.query.y);
    res.json({
        "methods": [
            {
                "name": "fv",
                "description": "Calculate the future value of money",
                "parameters": {
                    "pv": "Present value of money",
                    "n": "Number of years",
                    "r": "Interest rate"
                }
            },
            {
                "name": "pv",
                "description": "Calculate the present value of money",
                "paramteres": {
                    "fv": "Future value of money",
                    "n": "Number of years",
                    "r": "Interest rate"
                }
            },
            {
                "name": "dt",
                "description": "Calculate the time to double the money",
                "parameters": {
                    "r": "Interest rate"
                }
            },
            {
                "name": "per",
                "description": "Calculate the pepetuity value to get infinite dividend",
                "parameters": {
                    "d": "Desire dividend value",
                    "r": "Interest rate"
                }
            },
            {
                "name": "pmt",
                "description": "Calculate the monthly payment of loan",
                "parameters": {
                    "loan": "Loan amount",
                    "n": "Total monthly payments",
                    "r": "Interest rate"
                }
            }
        ]
    })
})

app.get('/fv', (req, res) => {
    var pv = parseFloat(req.query.pv)
    var n = parseFloat(req.query.n)
    var r = parseFloat(req.query.r)

    if (isNaN(pv) 
        || isNaN(n)
        || isNaN(r)) {
        res.json({
            "error": "not all input parameters are provided"
        })
    }
    else {
        var fv = pv * Math.pow(1+r/100, n)

        res.json({
            pv: pv,
            n: n,
            r: r,
            fv: fv
        })
    }    
})

app.get('/pv', (req, res) => {
    var fv = parseFloat(req.query.fv)
    var n = parseFloat(req.query.n)
    var r = parseFloat(req.query.r)

    if (isNaN(fv) 
        || isNaN(n)
        || isNaN(r)) {
        res.json({
            "error": "not all input parameters are provided"
        })
    }
    else {
        var pv = fv / Math.pow(1+r/100, n)

        res.json({
            pv: pv,
            n: n,
            r: r,
            fv: fv
        })        
    }
})

app.get('/dt', (req, res) => {
    var r = parseFloat(req.query.r)

    if (isNaN(r)) {
        res.json({
            "error": "not all input parameters are provided"
        })
    }
    else {    
        var dt = Math.log(2) / Math.log(1 + r/100);

        res.json({
            r: r,
            dt: dt
        })
    }
})

app.get('/per', (req, res) => {
    var d = parseFloat(req.query.d)
    var r = parseFloat(req.query.r)

    if (isNaN(r) 
        || isNaN(d)) {
        res.json({
            "error": "not all input parameters are provided"
        })
    }
    else {
        var per = d / (r/100)
        
        res.json({
            d: d,
            r: r,
            per: per
        })
    }
})

app.get('/pmt', (req, res) => {
    var loan = parseFloat(req.query.loan)
    var n = parseFloat(req.query.n)
    var r = parseFloat(req.query.r)/100
    
    if (isNaN(loan) 
        || isNaN(n)
        || isNaN(r)) {
        res.json({
            "error": "not all input parameters are provided"
        })
    }
    else {
        var interestTerm = Math.pow((1+r/12), n)
        var pmt = (loan * r/12) / (1 - (1/interestTerm))
    
        res.json({
            loan: loan,
            n: n,
            r: r*100,
            pmt: pmt
        })
    }
})

app.listen(port, () => {
    console.log(`listening on port ${port}`)
})
var express = require('express')

var port = 5000
var app = express()

app.get('/', (req, res) => {    

    var x = parseFloat(req.query.x);
    var y = parseFloat(req.query.y);
    res.json({
        "methods": [
            {
                "name": "fv",
                "description": "Calculate the future value of money",
                "parameters": {
                    "pv": "Present value of money",
                    "n": "Number of years",
                    "r": "Interest rate"
                }
            },
            {
                "name": "pv",
                "description": "Calculate the present value of money",
                "paramteres": {
                    "fv": "Future value of money",
                    "n": "Number of years",
                    "r": "Interest rate"
                }
            },
            {
                "name": "dt",
                "description": "Calculate the time to double the money",
                "parameters": {
                    "r": "Interest rate"
                }
            },
            {
                "name": "per",
                "description": "Calculate the pepetuity value to get infinite dividend",
                "parameters": {
                    "d": "Desire dividend value",
                    "r": "Interest rate"
                }
            },
            {
                "name": "pmt",
                "description": "Calculate the monthly payment of loan",
                "parameters": {
                    "loan": "Loan amount",
                    "n": "Total monthly payments",
                    "r": "Interest rate"
                }
            }
        ]
    })
})

app.get('/fv', (req, res) => {
    var pv = parseFloat(req.query.pv)
    var n = parseFloat(req.query.n)
    var r = parseFloat(req.query.r)

    if (isNaN(pv) 
        || isNaN(n)
        || isNaN(r)) {
        res.json({
            "error": "not all input parameters are provided"
        })
    }
    else {
        var fv = pv * Math.pow(1+r/100, n)

        res.json({
            pv: pv,
            n: n,
            r: r,
            fv: fv
        })
    }    
})

app.get('/pv', (req, res) => {
    var fv = parseFloat(req.query.fv)
    var n = parseFloat(req.query.n)
    var r = parseFloat(req.query.r)

    if (isNaN(fv) 
        || isNaN(n)
        || isNaN(r)) {
        res.json({
            "error": "not all input parameters are provided"
        })
    }
    else {
        var pv = fv / Math.pow(1+r/100, n)

        res.json({
            pv: pv,
            n: n,
            r: r,
            fv: fv
        })        
    }
})

app.get('/dt', (req, res) => {
    var r = parseFloat(req.query.r)

    if (isNaN(r)) {
        res.json({
            "error": "not all input parameters are provided"
        })
    }
    else {    
        var dt = Math.log(2) / Math.log(1 + r/100);

        res.json({
            r: r,
            dt: dt
        })
    }
})

app.get('/per', (req, res) => {
    var d = parseFloat(req.query.d)
    var r = parseFloat(req.query.r)

    if (isNaN(r) 
        || isNaN(d)) {
        res.json({
            "error": "not all input parameters are provided"
        })
    }
    else {
        var per = d / r
        
        res.json({
            d: d,
            r: r,
            per: per
        })
    }
})

app.get('/pmt', (req, res) => {
    var loan = parseFloat(req.query.loan)
    var n = parseFloat(req.query.n)
    var r = parseFloat(req.query.r)/100
    
    if (isNaN(loan) 
        || isNaN(n)
        || isNaN(r)) {
        res.json({
            "error": "not all input parameters are provided"
        })
    }
    else {
        var interestTerm = Math.pow((1+r/12), n)
        var pmt = (loan * r/12) / (1 - (1/interestTerm))
    
        res.json({
            loan: loan,
            n: n,
            r: r*100,
            pmt: pmt
        })
    }
})

app.listen(port, () => {
    console.log(`listening on port ${port}`)
})
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Categories

%d bloggers like this: