Skip to content

Instantly share code, notes, and snippets.

@myndzi
Last active August 29, 2015 14:23
Show Gist options
  • Save myndzi/85a5d193862cde73b3c2 to your computer and use it in GitHub Desktop.
Save myndzi/85a5d193862cde73b3c2 to your computer and use it in GitHub Desktop.
var Promise = require('bluebird');
var mysql = require('mysql');
var fs = require('fs');
var args = process.argv;
// Configure MySql connection
var con = Promise.promisifyAll(mysql.createConnection({
host: 'localhost',
user: 'friroot',
password: 'friserver2015',
database: 'naviserver'
}));
// Attempt to establish MySql connection
con.connectAsync()
.then(function () {
console.log('Connection to mysql database established.');
return import_locations();
})
.catch(function (err) {
console.log('Could not connect to mysql database: ' + error.message);
})
.finally(function () {
con.destroy();
});
function import_locations() {
// Check if user has provided name of the json locations file
if(args.length < 3) {
console.log('Missing locations import file.');
return;
}
console.log('Importing file: ' + args[2]);
// Attempt to parse locations import file
var json = JSON.parse(fs.readFileSync('./' + args[2], 'utf8'));
console.log('Successfully parsed ' + args[2] + '.');
var name = json.name; // Map name
var floor = json.floor; // Name of the floor
var locations = json.locations; // Reference points
console.log('Inserting ' + locations.length + ' rows.');
// using reduce here for the side effect of running in sequence
return Promise.reduce(locations, function (location) {
params = {
x: location.x,
y: location.y,
name: name,
floor: floor,
mag_strength: location.magnetic
};
signals = location.signals;
// Insert location if successful id is returned to be able to insert
// signals associated with location in bulk.
return con.queryAsync('INSERT INTO locations SET ?', params)
.then(function (result) {
// Access point to which signal results belong to
var id = result.insertId;
// Access point list associated with location
var access_points = [];
for(var j = 0; j < signals.length; j++) {
signal = signals[j];
access_points.push([id, signal.bssid, signal.level]);
}
// Bulk insert all signals for this location
return con.queryAsync('INSERT INTO signals (location_id, bssid, level) VALUES ?', [access_points]);
});
}).tap(function () {
console.log('Map and location data imported.');
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment