Created
August 6, 2015 09:13
-
-
Save david90/0e9a74269037c6ea1731 to your computer and use it in GitHub Desktop.
Simple Event tracking Server that insert records to MySQL (express, mysql module needed)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Server monitor */ | |
// require('newrelic'); | |
var mysql = require('mysql'); | |
var express = require('express'); | |
var app = express(); | |
var eventsCollection; | |
var sessionsCollection; | |
/** MySQL Settings **/ | |
var connection = mysql.createConnection({ | |
host : '***', | |
user : '***', | |
password : '***', | |
database : '***' | |
}); | |
/** End MySQL Settings **/ | |
app.get('/iphone/log_metrics.json', function(req, res) { | |
res.contentType('application/json'); | |
res.json({status:'ok'}); | |
var params = req.query; | |
var events = req.query.events; | |
delete params["events"]; | |
if(events){ | |
var json = JSON.parse(events); | |
insertEvents(json, params); | |
} | |
}); | |
function insertEvents(events, params) { | |
events.forEach(function(item) { | |
insertEvent(item, params); | |
}); | |
} | |
function insertEvent(item, params) { | |
Object.keys(params).forEach(function(key) { | |
if (key=='timestamp') { | |
if (key in item) { | |
item['date'] = new Date(item[key]*1000); | |
} else { | |
item['date'] = new Date(params[key]*1000); | |
} | |
} | |
if (!(key in item)) { | |
item[key] = params[key]; | |
} | |
}); | |
if(item['attributes'] !== undefined) item['attributes'] = JSON.stringify(item['attributes']); | |
var query = connection.query('INSERT INTO EVENTS SET ?', item, function(err, result) { | |
// console.log("Adding event"+item['name']); | |
if(err) console.log(err); | |
}); | |
} | |
function init(){ | |
/* connect MySQL */ | |
connection.connect(function(err){ | |
if(!err) { | |
console.log("Database is connected ... \n\n"); | |
var port = 8000; | |
app.listen(port); | |
console.log("Start Server on port:" + port); | |
} else { | |
console.log("Error connecting database ... \n\n"); | |
} | |
}); | |
} | |
init(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment