Setting up Server.JS

To start with adding the following modules to you package.json using
npm install --save body-parser express http moment winston
This will save it in you package.json file.

var express = require('express');
 var app = express();
 var bodyParser = require('body-parser');
 var fs = require('fs');
 var router = express.Router();

app.get('/', function(req,res){
 res.send('hello world');
 });

app.listen(4000, function(){
 console.log('started server on port 4000');
 });

This just gets up up and running. If you run node server.js and point your browser to localhost:4000. You should see a lovely hello page. If not, now is a good time to debug what is wrong.

Now that we have that part working lets add some more useful code.

I am going to leave it to the reader to install MySQL. Just follow the plethora of instructions available for your OS.

I like to keep create reusable code when possible. Here is a file named utils/readMySQL.js. This is used by the server.js file to pull data out of the database.

var mysql = require('mysql');

var details = {
 host: 'localhost',
 user: 'username',
 password: 'password',
 database: 'weather_data'
 };

var readLatestValues = function(tableName, count, resultCallback) {
 var connection = mysql.createConnection(details.weatherConnectionDetails);

if(count <=0){
 count = 1;
 }
 var latestEntryQuery = 'SELECT * from ' + tableName + ' ORDER By id DESC LIMIT ' + count;

var result = null;
 connection.connect(function(err){
 if(err){
 console.log('there was an error' + err);
 }else{
 //console.log('Connection sucessfull');
 }
 });

result = connection.query(latestEntryQuery, function(err, rows, fields){
 if(err){
 console.log('there was an error' + err);
 throw err;
 }else{
 //console.log(rows);
 //console.log(resultCallback.toString());
 resultCallback(err,rows);
 }

});

connection.end(function(err){
 if(err){
 console.log('Error Closing Connection' + err);
 }else{
 //console.log('connection closed');
 }
 });

};

module.exports = {
 readLatestValues: readLatestValues
 };

Now for an updated server.js file where we can server up content as a rest interface.
but first let’s update our package.json so that we can take advantage our some new functionality. We are going to add winston which is a logger. You always want to log events in your app. Once you start server.js as a

npm install --save mysql winston moment

server.js

var express = require('express');
 var app = express();
 var bodyParser = require('body-parser');
 var mysql = require('./utils/readMySQL');
 var moment = require('moment');
 var winston = require('winston');
 var http = require('http');
 var fs = require('fs');

app.use(bodyParser.urlencoded({extended: true}));
 app.use(bodyParser.json());

var router = express.Router();
 var logFile = '../logs/' + moment().format("YYYYMMDD_hhmmss")+'.log';

var winstonOptions = {
 filename: logFile,
 handleExceptions: true,
 humanReadableUnhandledException: true,
 level: 'info',
 json: true,
 timestamp: true
 };

winston.add(winston.transports.File, winstonOptions);

app.get('/', function(req,res){
 res.send('hello world');
 });

app.get('/weather', function(req,res){
 var res = res;
 var queryQty = req.query.qty;
 if(!queryQty || queryQty < 1){
 queryQty = 1;
 }
 mysql.readLatestValues('weather',queryQty,function(err, result){
 res.json({message: result});
 });
 });

app.get('/latestWeather', function(req,res) {
 var res = res;
 mysql.readLatestValues('weather', 1, function(err,result){
 res.json(result);
 });
 });

app.listen(4000, function(){
 winston.log('INFO','server started on 4000');
 });

Now we can get to the data using web calls.

Let’s start the server again by running node serve and point the browser to localhost:4000/latestWeather. We should see the JSON formatted response of our data.

screenshot-from-2016-11-01-22-27-38

Advertisements

About isaacdrose

Software Engineer. All around nerdy guy.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: