Node.js, Express.js and sqllite3.js - node.js

I have a problem with object attributes in Node.js. While attributes are set as expected in the test object, the same doesn't work for my articles object. The difference I see is that the functions of articles are called asynchronously. I must confess that I am a bit lost...
Here is app.js, that instantiates the test object and the articles object.
/**
* Load express.
*/
var express = require('express');
var app = express();
/**
* Load articles.
*/
var articles = require('./article.js');
var l_articles = new articles.Articles();
var test = require('./test.js');
var l_test = new test.Test();
app.get('/', function (req, res) {
console.log(l_test.get());
l_test.set('it is', 'midnight');
console.log(l_test.get());
articles.Articles.get(1);
res.send('OK');
})
app.listen(3001, function () {
console.log(l_test.get());
l_test.set('goodbye', 'sunshine');
console.log(l_test.get());
})
Here is my fairly simple test.js :
var app = require('./app.js');
function Test() {
this.timestamp = new Date();
console.log(this.timestamp);
this.attribute1 = 'hello';
this.attribute2 = 'world';
}
Test.prototype.get = function() {
console.log(this.timestamp);
return (this.attribute1 + ' ' + this.attribute2);
}
Test.prototype.set = function(p_param1, p_param2) {
console.log(this.timestamp);
this.attribute1 = p_param1;
this.attribute2 = p_param2;
}
module.exports = {
Test: Test
};
Here is my fairly simple article.js :
var sqlite3 = require('sqlite3').verbose();
var app = require('./app.js');
function Articles(p_id) {
this.timestamp = new Date();
console.log(this.timestamp);
this.db = new sqlite3.Database('./gescom.sqlite');
if (p_id == undefined) {
this.db.all('SELECT * FROM T_ARTICLE', this.load);
} else {
this.db.all('SELECT * FROM T_ARTICLE WHERE id = ' & p_id, this.load);
}
}
Articles.prototype.load = function(p_err, p_rows) {
console.log(this.timestamp);
var ids = [];
var articles = [];
p_rows.forEach(function(p_row) {
ids.push(p_row.ID);
articles.push([p_row.ID, p_row.SHORT_NAME]);
});
this.ids = ids;
this.articles = articles;
console.log(this.ids.length + ' articles loaded from database.');
}
Articles.prototype.get = function (p_id) {
console.log(this.timestamp);
var l_return;
if ((this.ids == undefined) || (this.articles == undefined)) {
console.log('No articles loaded from database.');
} else {
console.log(this.ids.length + ' articles loaded from database.');
if (p_id == undefined) {
l_return = this.articles;
} else {
if (this.ids.indexOf(p_id) != undefined) {
l_return = (this.articles[this.ids.indexOf(p_id)]);
} else {
l_return = undefined;
}
}
}
return l_return;
}
module.exports = {
Articles: Articles
};

Related

Mongodb UseUnifiedTopology: True causes connection errors in my code

I have a small app written in Node.js that downloads some data from an API, and then saves it into a MongoDB. When I have useunifiedtopology: false my code runs fine, connects to the mongodb fine and updates everything fine.
When I set useunifiedtopolgy: true I get the following errors
MongoError: Cannot use a session that has ended
Here is what I am trying to accomplish...I can't for the life of me figure out where it's going wrong. If I remove the db.close() from dbupdater.js, it works, but the app just hangs.
Here is how I am going about things...
It should also be noted, that if I remove the multiple locations and extraction calls from below, then it does work fine. The errors noted above when using useunifiedtopology: false only seem to happen when I am doing multiple calls to the dbupdater module. So, to be clear, if I just hit the API once, and do one call to dbupdater, it works fine. If I call the API and the dbupdater function multiple times, it fails with the error:
MongoError: Cannot use a session that has ended.
app.js Contents:
const Downloader = require('./modules/Downloader')
const dbupdater = require('./modules/dbUpdater')
var Locations = ['Location1','Location2']
var ExtractionTypes = ['Extraction1','Extraction2','Extraction3' ]
var interval = 60000; //API Request Delay in MS
var promise = Promise.resolve();
function main() {
Locations.forEach(location => {
promise = promise.then(function(){
ExtractionTypes.forEach(extraction =>{
promise = promise.then(function(){
talonDownloader(location,extraction,function(data){
if (data == null) {
console.log(`No ${extraction} Data Recieved for period requested.`)
}
else {
dbupdater(extraction,data)
}
})
return new Promise(function (resolve) {
setTimeout(resolve, interval)
})
})
})
return new Promise(function (resolve) {
setTimeout(resolve, interval)
})
})
})
}
main();
Then here is the code for my dbupdater...
dbudater.js
module.exports = function (extraction,data) {
const MongoClient = require('mongodb').MongoClient;
const date = require('date-and-time');
const crypto = require('crypto')
const dburl = "mongodb://localhost:27017/";
const dbName = 'palDB'
//Initialize Date Information
const now = new Date()
const todayDate = date.format(now, 'DD-MMM-YYYY')
if (extraction == 'operation') {
var collectionName = 'operations'
var indexValue = 'ACTIVITY_ID'
updateDBGeneral();
}
else if (extraction == 'aircraft') {
var collectionName = 'aircraft'
var indexValue = 'AIRCRAFT_ID'
updateDBGeneral();
updateDBHistorical();
}
else if (extraction == 'cancelanalysis') {
var collectionName = 'cancelAnalysis'
var indexValue = 'SCH_ACT_ID'
updateDBGeneral();
}
else if (extraction == 'dailyflylog') {
var collectionName = 'dfl'
var indexValue = 'SCH_ACT_ID'
updateDBGeneral();
}
else if (extraction == 'instructor') {
var collectionName = 'instructor'
var indexValue = 'ETA_ID'
updateDBGeneral();
}
else if (extraction == 'resschedproductivity') {
var collectionName = 'resSchedProductivity'
var indexValue = 'opid'
updateDBGeneral();
}
else if (extraction == 'student') {
var collectionName = 'student'
var indexValue = 'ETA_ID'
updateDBGeneral();
}
else if (extraction == 'trainingrecord') {
var collectionName = 'trgrec'
var indexValue = 'STUDENT_REGISTRATION_ID'
updateDBGeneral();
}
else if (extraction == 'studentprogression') {
var collectionName = 'studentProgression'
var indexValue = 'studentProgIndex'
updateDBGeneral();
}
//Initialize DB Updater functions
function updateDBGeneral(){
MongoClient.connect(dburl,{useNewUrlParser: true, useUnifiedTopology: true})
.then((db) => {
var dbo = db.db(dbName);
console.log(`Connection Established to ${dbo.databaseName} database.`)
data.forEach(element => {
if (indexValue == 'opid') {
element[indexValue] = crypto.createHash('md5').update(element.CAL_DATE + element.RES_TYPE_ID).digest('hex'); //Add Value to filter on
var filter = {[indexValue]: element[indexValue]};
} else if (indexValue =='studentProgIndex'){
element[indexValue] = crypto.createHash('md5').update(element.PERS_REGISTER_ID + element.UNIT + element.ACT_START).digest('hex'); //Add value to filter on
var filter = {[indexValue]: element[indexValue]}
} else var filter = {[indexValue]: element[indexValue]}
dbo.collection(collectionName)
.updateOne(filter, {$set:element},{upsert:true})
.then( result => db.close())
.catch( err => console.log(err));
})
})
.catch( err => console.log(err));
}
function updateDBHistorical(){
}
}

Why doesn't my async function return any result?

I wrote this small program to fetch data. This however is done async. Since I nonetheless need to use the function holeVertreter(kzl) as a function in another module, I'd like to get a return value which I can eventually pass on.
Excuse my spaghetti code (I usually prettify the code when I am done with my task ...).
Credentials are stored in a file and are therefore not found in this file.
I'd like to end up with "vertreter" as a return value.
Thank you in advance.
const node = require("deasync");
const DSB = require('dsbapi');
const tabletojson = require('tabletojson');
const https = require('https');
const cred = require("./vertrCred");
const dsb = new DSB(cred["dsb"]["user"], cred["dsb"]["passw"]); //Sanitized - no Credentials here
//Stackoverflow 2332811
String.prototype.capitalize = function(lower) {
return (lower ? this.toLowerCase() : this).replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); });
};
function holePlan(kuerzel) {
dsb.fetch()
.then(data => {
const timetables = DSB.findMethodInData('timetable', data);
const tiles = DSB.findMethodInData('tiles', data);
var tilesStr = JSON.stringify(tiles["data"][0]["url"]);
var url = JSON.parse(tilesStr);
https.get(url, (resp) => {
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end',() => {
var tableasjson = tabletojson.convert(data);
var erstetab = tableasjson[0];
var zweitetab = tableasjson[1];
var drittetab = tableasjson[2];
var viertetab = tableasjson[3];
var fuenftetab = tableasjson[4];
var sechstetab = tableasjson[5];
var siebtetab = tableasjson[6];
var achtetab = tableasjson[7];
if (typeof kuerzel === "undefined")
{
var regenechse = '(Aaa|Aaa[A-Za-z?]|[A-Za-z?]Aaa)';
}
else {
var name = kuerzel.capitalize(true);
var regenechse = '('+name+'|'+name+'[A-Za-z?]|[A-Za-z?]'+name+')';
}
const regex = new RegExp(regenechse,'g');
var sammel = Object.assign(drittetab,fuenftetab);
var z= 0;
var vertreter = {}
var y = JSON.parse(JSON.stringify(sammel));
for (i=0;i<y.length;i++) {
if (typeof y[i].Vertreter =='undefined') {
}
else {
if(y[i].Vertreter.match(regex))
{
z += 1;
vertreter[z] = y[i];
}
}
}
if (z == 0) {
// console.log("Es gibt nichts zu vertreten");
}
else {
//console.log("Es werden "+z+" Stunden vertreten");
return (vertreter);
} ;
});
})
})
.catch(e => {
// An error occurred :(
console.log(e);
});
}
//Stackoverflow
function warte(promise) {
var done = 0;
var result = null;
promise.then(
function (value) {
done = 1;
result = value;
return (value);
},
function (reason) {
done = 1;
throw reason;
}
);
while (!done)
node.runLoopOnce();
return (result);
}
function holeVertretung(kzl) {
var aufgabe = new Promise((resolve,reject) => {
setTimeout(resolve,1000,holePlan(kzl));
});
var ergebnis = warte(aufgabe);
if (typeof ergebnis === "undefined") {
console.log("Mist");
}
else {
console.log(ergebnis);
}
return ergebnis;
}
holeVertretung("Aaa");
That's not the right way to work with promises. If you do such infinite loop, it beats the whole purpose of using promises. Instead, return value from the promise, and use async-await like this:
function warte(promise) {
var done = 0;
var result = null;
return promise.then(
...
}
async function holeVertretung(kzl) {
var aufgabe = new Promise((resolve, reject) => {
setTimeout(resolve, 1000, holePlan(kzl));
});
var ergebnis = await warte(aufgabe);
...
If async-await does not work for some reason, use then clause:
warte(aufgabe).then(value => {
var ergebnis = value;
});

node js post request

Success localhost response
Cannot GET /u/coupons at server
Frontend script for post
<script>
var count = document.getElementById("count");
var len = document.getElementById("length");
var pattern = document.getElementById("pattern");
document.getElementById('coupons-button').onclick = function()
{
if(count.value!=="" && len.value!=="")
{
const genReq = new XMLHttpRequest();
let url = `count=${encodeURI(count.value)}&` +
`len=${encodeURI(len.value)}&` +
`pattern=${encodeURI(pattern.value)}`;
genReq.open('POST',`/u/coupons?${url}`,true);
genReq.send();
genReq.onreadystatechange = e => {
if(genReq.readyState === 4 && genReq.status === 200){
let gen = JSON.parse(genReq.response);
if (gen.state === "SUCCESS")
{
var coupons = gen.coupons;
for(var i=0;i<coupons.length;i++)
{
var div = document.createElement('div');
var text = document.createTextNode(coupons[i]);
div.appendChild(text);
document.getElementById('coupons-check').appendChild(div);
}
} else {
var div = document.createElement('div');
var text = document.createTextNode("FAIL TO GENERATE");
div.appendChild(text);
document.getElementById('coupons-check').appendChild(div);
}
}
}
}
}
Server script
admin.post( '/u/coupons' ,(req,res)=>{
let params = getParameters(req);
CouponWorker.generateCoupons({
"len":decodeURI(params.len),
"count":decodeURI(params.count),
"pattern":decodeURI(params.pattern)
}).then((_res) =>{
console.log(_res)
if(_res.success === true)
{
res.status(200).json({
"state":"SUCCESS",
"coupons":_res.coupons
});
}
else{
res.status(200).json({"state" : "FAILED"});
}
});
});
CouponWorker
const firebase = require('./Database');
const voucher_codes = require('voucher-code-generator');
exports.generateCoupons = function(params)
{
var len = params.len;
var count = params.count;
var pattern = params.pattern;
//pattern = pattern.replace(/1/g,'#');
const cpn_db = firebase.firebase.database();
var coupons;
return new Promise((resolve,reject)=>{
coupons = voucher_codes.generate({
length:len,
count:count,
prefix:"AMP-",
pattern: '####-####',
charset:"0123456789ABCDEFGHIJKLMNOPQRSTUVXYZ"
});
if(coupons!==null)
{
for(var i =0;i<count;i++)
{
cpn_db.ref('coupons/cid-'+coupons[i]).set({
"addedOn": getDateTime(),
"code" : coupons[i],
"amount" : 20,
"expireDate" : null,
"isActive" : true,
"isDeleted":false
});
}
resolve({
"success":true,
"coupons":coupons
});
}
else
{
resolve({
"success":false
});
}
});
}
Above given snaps shows the same code running on localhost and server,
localhost working fine,giving output and saving data to firbase while server response 404 not found resource.
I can not find the reason of this error.I tried url req on postman and responses are the same as above

How to handle the node server side with react

Im working on react and node project. Im new to both technologies, and i developed a system for my internship. But I feel like, I didn't handle the server side (Node part) properly. This is my server side file. It container almost 700 lines. Do I have to break this page in to several pages? If so, how exactly I should do it? Can someone give me a suggestion please. The application is working as expected. I just want to clean the code in the server side. I used express framework with node.
var express = require('express');
var mysql = require('mysql');
var _ = require('underscore');
var crypto = require('crypto');
var app = express();
var connections = [];
var title = 'Fishery Logistics';
var flds = [];
var currentFld = '';
var fldDetails = [];
var lfrSaved = false;
var userSiteInfoSaved = false;
var userList = [];
var userTypes = [];
var validUserName = false;
var fldNumbers = [];
var productCodes = [];
var containerTypes = [];
var areaCodes = [];
var fldRows = 0;
var fldInfo = {};
var productInfo = {};
var weighInList = {};
var weighInSaved = false;
var weighInNumbers = [];
var weighInWeights = [];
var fldHeaderInfo = [];
var weighInHeaderInfo = [];
var fldWeights = [];
var userDeleted = false;
// From where express should access our files
app.use(express.static('./public'));
app.use(express.static('./node_modules/bootstrap/dist'));
var server = app.listen(process.env.PORT || 3000);
// Creating a socket server which is also listeing to localhost:<port>
var io = require('socket.io').listen(server);
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: '',
database: 'fish_landing'
});
io.sockets.on('connection', function(socket) {
// Load fld list relevant to a LFR
socket.on('lfrFldListLoad', function(payload) {
var lfr_id = payload.lfrId;
var sql_lfr_fld_list = 'SELECT F.fld_id, F.fld_number, DATE_FORMAT(F.landed_date, "%Y-%m-%d") AS "landed_date", F.vessel_name, F.port_name, F.transport_company_name, F.driver_name, truck_number, FS.status ' +
'FROM fld F, fld_status FS, lfr L ' +
'WHERE F.status_id = FS.status_id ' +
'AND F.lfr_id = L.lfr_id ' +
'AND L.lfr_id = ' + lfr_id +
' ORDER BY F.fld_id DESC';
connection.query(sql_lfr_fld_list, function(error, result) {
if (error) {
console.log(error);
}
if (result.length !== 0) {
flds = result;
io.sockets.emit('lfrFldListLoaded', flds);
} else {
console.log('No Records Found')
}
});
});
// Load fld with all the details
socket.on('fldViewLoad', function(payload) {
var fld_id = payload.fldId;
var sql_fld_by_id =
'SELECT F.fld_id, F.fld_number, DATE_FORMAT(F.landed_date, "%Y-%m-%d") AS "landed_date", DATE_FORMAT(F.landed_date, "%T") AS "landed_time", ' +
'F.port_name, F.vessel_name, F.skipper_name, F.transport_company_name, F.truck_number, F.driver_name, F.driver_license, F.vehicle_clean, ' +
'F.vehicle_refrigerated, F.containers_clean, F.containers_iced, F.skipper_signature, F.supervisor_signature, F.lfr_staff_signature, ' +
'F.skipper_signature_time, F.supervisor_signature_time, F.lfr_staff_signature_time, F.comment, FS.status, CONCAT(U.first_name, " ", U.last_name) AS "full_name", ' +
'DATE_FORMAT(F.fld_created_time, "%Y-%m-%d") AS "fld_created_date", DATE_FORMAT(F.fld_created_time, "%T") AS "fld_created_time" ' +
'FROM fld F, fld_status FS, user_personal_info U ' +
'WHERE F.status_id = FS.status_id ' +
'AND F.fld_created_user_id = U.user_id ' +
'AND F.fld_id = "' + fld_id + '"';
var sql_fld_detail_list =
'SELECT FD.fld_detail_id, SP.species, PS.state, C.container, FD.no_of_containers, FD.fld_id ' +
'FROM fld_details FD, species SP, processed_state PS, container C, fld F ' +
'WHERE F.fld_id = FD.fld_id ' +
'AND SP.species_id = FD.species_id ' +
'AND PS.state_id = FD.state_id ' +
'AND C.container_id = FD.container_id ' +
'AND F.fld_id = "' + fld_id + '"';
connection.query(sql_fld_by_id, function(errorFld, resultFld) {
if (errorFld) {
console.log(errorFld);
}
if (resultFld.length !== 0) {
currentFld = resultFld;
connection.query(sql_fld_detail_list, function(errorFldDetails, resultFldDetails) {
if (errorFldDetails) {
console.log(errorFldDetails);
} else {
fldDetails = resultFldDetails;
io.sockets.emit('fldViewLoaded', currentFld, fldDetails);
}
});
} else {
console.log('Fld Length Error')
}
});
});
// Save company info
socket.on('saveCompanyInfo', function(payload) {
var companyName = payload.companyName;
var registrationNo = payload.registrationNo;
var landlineNo = payload.landlineNo;
var mobileNo = payload.mobileNo;
var emailAddress = payload.emailAddress;
var companyLogo = payload.companyLogo;
var jsonFile = payload.jsonFile;
var sql_save_company_info =
`INSERT INTO lfr (lfr_name, registration_number, landline_number, mobile_number, email_address, lfr_logo, json_file)
VALUES ('${companyName}', '${registrationNo}', '${landlineNo}', '${mobileNo}', '${emailAddress}', '${companyLogo}', '${jsonFile}')`;
connection.query(sql_save_company_info, function(errorLfrInfo, resultLfrInfo) {
if (errorLfrInfo) {
lfrSaved = false;
console.log(errorLfrInfo);
}
if (resultLfrInfo) {
lfrSaved = true;
} else {
lfrSaved = false;
}
io.sockets.emit('companyInfoSaved', lfrSaved);
});
});
// Load user list for lfr
socket.on('userListLoad', function(payload) {
var lfrId = payload.lfrId;
var load_user_list =
`SELECT USI.user_id, USI.user_name, UT.user_type, USI.email_address, USI.passcord, US.status_type
FROM user_site_info USI, user_types UT, user_status US
WHERE USI.user_type_id = UT.user_type_id
AND USI.user_status_id = US.user_status_id
AND lfr_id = ${lfrId}`;
connection.query(load_user_list, function(errorUserList, resultUserList) {
if (errorUserList) {
console.log(errorUserList);
} else {
userList = resultUserList;
io.sockets.emit('userListLoaded', userList);
}
});
});
// Load organization form
socket.on('loadOrganization', function() {
io.sockets.emit('organizationLoaded');
});
// Load main form
socket.on('loadMain', function() {
io.sockets.emit('mainLoaded');
});
// Delete user
socket.on('deleteUser', function(payload) {
var lfrId = payload.lfrId;
var userId = payload.userId;
var delete_user =
`UPDATE user_site_info
SET user_status_id = '2'
WHERE user_id = ${userId}`;
var load_user_list =
`SELECT USI.user_id, USI.user_name, UT.user_type, USI.email_address, USI.passcord, US.status_type
FROM user_site_info USI, user_types UT, user_status US
WHERE USI.user_type_id = UT.user_type_id
AND USI.user_status_id = US.user_status_id
AND lfr_id = ${lfrId}`;
connection.query(delete_user, function(error, result) {
if (error) {
console.log(error);
}
if (result) {
connection.query(load_user_list, function(errorUserList, resultUserList) {
if (errorUserList) {
console.log(errorUserList);
} else {
userDeleted = true;
userList = resultUserList;
io.sockets.emit('userDeleted', userDeleted, userList);
}
});
} else {
userDeleted = false;
}
});
});
// Delete weigh in
socket.on('deleteWeighIn', function(payload) {
var weighInId = payload.weighInId;
var sql_delete_weigh_in =
`DELETE FROM weigh_in
WHERE weigh_in_id = ${weighInId}`;
var sql_delete_weigh_in_details =
`DELETE FROM weigh_in_details
WHERE weigh_in_id = ${weighInId}`;
connection.query(sql_delete_weigh_in, function(errorDeleteWightIn, resultDeleteWightIn) {
if (errorDeleteWightIn) {
console.log(errorDeleteWightIn);
}
connection.query(sql_delete_weigh_in_details, function(errorDeleteWightInDetails, resultDeleteWightInDetails) {
if (errorDeleteWightInDetails) {
console.log(errorDeleteWightInDetails);
}
if (resultDeleteWightInDetails) {
io.sockets.emit('weighInDeleted');
} else {
console.log('Weigh-In Deletion Error');
}
});
});
});
// Reset weigh-in list
socket.on('resetWeighInList', function() {
io.sockets.emit('weighInListReset');
});
// Save user site info
socket.on('saveUserSiteInfo', function(payload) {
var userName = payload.userName;
var userTypeId = payload.userType;
var emailAddress = payload.emailAddress;
var passcord = crypto.createHash('sha1').update(payload.passcord).digest("hex");
var userStatusId = 1;
var lfrId = payload.lfrId;
var sql_user_site_info =
`INSERT INTO user_site_info (user_name, user_type_id, email_address, passcord, user_status_id, lfr_id)
VALUES ('${userName}','${userTypeId}', '${emailAddress}', '${(passcord)}','${userStatusId}', '${lfrId}')`;
var load_user_list =
`SELECT USI.user_id, USI.user_name, UT.user_type, USI.email_address, USI.passcord, US.status_type
FROM user_site_info USI, user_types UT, user_status US
WHERE USI.user_type_id = UT.user_type_id
AND USI.user_status_id = US.user_status_id
AND lfr_id = ${lfrId}`;
connection.query(sql_user_site_info, function(errorUserInfo, resultUserInfo) {
if (errorUserInfo) {
userSiteInfoSaved = false;
console.log(errorUserInfo);
}
if (resultUserInfo) {
userSiteInfoSaved = true;
connection.query(load_user_list, function(errorUserList, resultUserList) {
if (errorUserList) {
console.log(errorUserList);
} else {
userList = resultUserList;
io.sockets.emit('userSiteInfoSaved', userSiteInfoSaved, userList);
}
});
} else {
console.log('User Info Saving Error')
}
});
});
// Save weigh in info
socket.on('saveWeighInRecord', function(payload) {
var fldId = payload.fldId;
var weighInId = payload.fldId;
var productId = payload.productId;
var containerId = payload.containerId;
var amount = payload.amount;
var netWeight = payload.netWeight;
var areaId = payload.areaId;
var userId = payload.userId;
// Check if the record is the first of the weigh in id,
var sql_check_weigh_in =
`SELECT * FROM weigh_in
WHERE weigh_in_id = '${weighInId}'`;
connection.query(sql_check_weigh_in, function(errorCheck, resultCheck) {
if (errorCheck) {
console.log(errorCheck);
}
// If there is no recrod related to weigh in id, create the weigh in id
if (resultCheck.length === 0) {
var sql_weigh_in_header =
`INSERT INTO weigh_in (weigh_in_id, fld_id, logged_user_id, created_time)
VALUES('${weighInId}', '${fldId}', '${userId}', NOW())`;
connection.query(sql_weigh_in_header, function(errorHeader, resultHeader) {
if (errorHeader) {
console.log(errorHeader);
}
});
}
});
var sql_weigh_in_record =
`INSERT INTO weigh_in_details (product_id, container_id, number_of_containers, net_weight, area_id, weigh_in_id)
VALUES ('${productId}', '${containerId}','${amount}','${netWeight}','${areaId}','${weighInId}')`;
var sql_load_records =
`SELECT P.product_code, C.container, WD.number_of_containers, WD.net_weight, S.species_code, PS.state_code, G.grade, A.area_code
FROM product P, container C, species S, processed_state PS, grade G, area A, weigh_in_details WD
WHERE WD.product_id = P.product_id
AND WD.container_id = C.container_id
AND WD.area_id = A.area_id
AND P.species_id = S.species_id
AND P.state_id = PS.state_id
AND P.grade_id = G.grade_id
AND weigh_in_id = '${weighInId}'
ORDER BY weigh_in_detail_id ASC`;
connection.query(sql_weigh_in_record, function(errorRecord, resultRecord) {
if (errorRecord) {
console.log(errorRecord);
}
if (resultRecord) {
connection.query(sql_load_records, function(errorList, resultList) {
if (errorList) {
console.log(errorList);
} else {
weighInList = resultList;
io.sockets.emit('weighInRecordSaved', weighInList);
}
});
} else {
console.log('Weigh In Saving Error')
}
});
});
// Load user types
socket.on('loadUserTypes', function() {
var sql_user_types =
`SELECT user_type_id, user_type FROM user_types
ORDER BY user_type ASC`;
connection.query(sql_user_types, function(error, result) {
if (error) {
console.log(error);
}
if (result.length !== 0) {
userTypes = result;
io.sockets.emit('userTypesLoaded', userTypes);
} else {
console.log('User Type Error')
}
});
});
// Load weigh-in numbers
socket.on('loadWeighInNumbers', function(payload) {
var lfrId = payload.lfrId
var sql_load_weigh_in =
`SELECT W.weigh_in_id
FROM weigh_in W, fld F
WHERE W.weigh_in_id = F.fld_id
AND F.lfr_id = ${lfrId}`;
connection.query(sql_load_weigh_in, function(error, result) {
if (error) {
console.log(error);
}
if (result.length !== 0) {
weighInNumbers = result;
io.sockets.emit('weighInNumbersLoaded', weighInNumbers);
} else {
console.log('Weigh-In Error')
}
});
});
// Load fld, weigh-in weights
socket.on('loadWeighInWeights', function(payload) {
// weigh_in table weigh_in_id and fld table fld_id are same
var weighInId = payload.weighInId;
var sql_load_fld_weights =
`SELECT S.species, S.species_code, SUM(FD.no_of_containers * C.content_weight) AS 'fld_weight'
FROM fld_details FD, species S, container C
WHERE S.species_id = FD.species_id
AND FD.container_id = C.container_id
AND FD.fld_id = '${weighInId}'
GROUP BY S.species_code, 'fld_weight'
ORDER BY S.species_code`;
var sql_load_weigh_in_weights =
`SELECT S.species, S.species_code, SUM(WD.net_weight) AS 'weigh_in_weight'
FROM weigh_in_details WD, species S, product P, container C
WHERE P.species_id = S.species_id
AND WD.product_id = P.product_id
AND WD.container_id = C.container_id
AND WD.weigh_in_id = '${weighInId}'
GROUP BY S.species_code, 'weigh_in_weight'
ORDER BY S.species_code`;
var sql_load_fld_info =
`SELECT DATE_FORMAT(F.fld_created_time, "%Y-%m-%d") AS "fld_created_date", CONCAT(U.first_name, " ", U.last_name) AS "fld_created_by", COUNT(FD.fld_id) AS "fld_records"
FROM fld F, user_personal_info U, fld_details FD
WHERE F.fld_created_user_id = U.user_id
AND F.fld_id = FD.fld_id
AND F.fld_id = '${weighInId}'`;
var sql_load_weigh_info =
`SELECT DATE_FORMAT(created_time, "%Y-%m-%d") AS "weigh_in_created_date", CONCAT(U.first_name, " ", U.last_name) AS "weigh_in_created_by", COUNT(WD.weigh_in_id) AS "weigh_in_records"
FROM weigh_in W, user_personal_info U, weigh_in_details WD
WHERE W.logged_user_id = U.user_id
AND W.weigh_in_id = WD.weigh_in_id
AND W.weigh_in_id = '${weighInId}'`;
connection.query(sql_load_fld_weights, function(errorFldWeights, resultFldWeights) {
if (errorFldWeights) {
console.log(errorFldWeights);
}
if (resultFldWeights.length !== 0) {
connection.query(sql_load_weigh_in_weights, function(errorweighInWeights, resultWeighInWeights) {
if (errorweighInWeights) {
console.log(errorweighInWeights);
}
if (resultWeighInWeights.length !== 0) {
connection.query(sql_load_fld_info, function(errorFldInfo, resultFldInfo) {
connection.query(sql_load_weigh_info, function(errorWeighInInfo, resultWeighInInfo) {
fldWeights = resultFldWeights;
weighInWeights = resultWeighInWeights;
fldHeaderInfo = resultFldInfo;
weighInHeaderInfo = resultWeighInInfo;
io.sockets.emit('weighInWeightsLoaded', fldWeights, weighInWeights, fldHeaderInfo, weighInHeaderInfo);
});
});
} else {
console.log('Weigh-In Weights Error')
}
});
}
});
});
// Load weigh in combo boxes
socket.on('loadWeighInComboBoxes', function(payload) {
var lfr_id = payload.lfr_id;
var sql_load_fld_numbers = `
SELECT fld_id, fld_number FROM fld WHERE lfr_id = '${lfr_id}'
ORDER BY fld_number DESC `;
var sql_load_product_codes = `
SELECT product_id, product_code FROM product ORDER BY product_code ASC `;
var sql_load_containers = `
SELECT container_id, container FROM container WHERE lfr_id = ${lfr_id} ORDER BY container ASC`;
var sql_load_area_codes = `
SELECT area_id, area_code FROM area ORDER BY area_code ASC `;
connection.query(sql_load_fld_numbers, function(errorFld, resultFld) {
if (errorFld) {
console.log(errorFld);
}
connection.query(sql_load_product_codes, function(errorProducts, resultProducts) {
if (errorProducts) {
console.log(errorProducts);
}
connection.query(sql_load_containers, function(errorContainer, resultContainer) {
if (errorContainer) {
console.log(errorContainer);
}
connection.query(sql_load_area_codes, function(errorArea, resultArea) {
if (errorArea) {
console.log(errorArea);
}
fldNumbers = resultFld;
productCodes = resultProducts;
containerTypes = resultContainer;
areaCodes = resultArea;
io.sockets.emit('weighInComboBoxesLoaded', fldNumbers, productCodes, containerTypes, areaCodes);
});
});
});
});
});
// Get fld info and weigh in records that are relavent to weighInId
socket.on('loadFldWeighInInfo', function(payload) {
var fldId = payload.fldId;
var weighInId = payload.fldId;
var sql_get_fld_count =
`SELECT COUNT( * ) AS 'fld_rows'
FROM fld_details WHERE fld_id = '${fldId}'`;
var sql_get_fld_info =
`SELECT DATE_FORMAT(F.fld_created_time, "%Y-%m-%d") AS "fld_created_date", DATE_FORMAT(F.fld_created_time, "%T") AS "fld_created_time", CONCAT(U.first_name, " ", U.last_name) AS "created_by"
FROM fld F, user_personal_info U
WHERE F.fld_created_user_id = U.user_id
AND F.fld_id = '${fldId}'`;
var sql_load_records =
`SELECT P.product_code, C.container, WD.number_of_containers, WD.net_weight, S.species_code, PS.state_code, G.grade, A.area_code
FROM product P, container C, species S, processed_state PS, grade G, area A, weigh_in_details WD
WHERE WD.product_id = P.product_id
AND WD.container_id = C.container_id
AND WD.area_id = A.area_id
AND P.species_id = S.species_id
AND P.state_id = PS.state_id
AND P.grade_id = G.grade_id
AND weigh_in_id = '${weighInId}'
ORDER BY weigh_in_detail_id ASC `;
connection.query(sql_get_fld_count, function(errorFldCount, resultFldCount) {
if (errorFldCount) {
console.log(errorFldCount);
}
connection.query(sql_get_fld_info, function(errorFldInfo, resultFldInfo) {
if (errorFldInfo) {
console.log(errorFldInfo);
}
connection.query(sql_load_records, function(errorList, resultList) {
if (errorList) {
console.log(errorList);
} else {
fldRows = resultFldCount;
fldInfo = resultFldInfo;
weighInList = resultList;
io.sockets.emit('fldWeighInInfoLoaded', fldRows, fldInfo, weighInList);
}
});
});
});
});
// Get product info
socket.on('loadProductInfo', function(payload) {
var productId = payload.productId;
var sql_get_product_info =
`SELECT P.product_code, S.species_code, PS.state_code, G.grade
FROM product P, species S, processed_state PS, grade G
WHERE P.species_id = S.species_id
AND P.state_id = PS.state_id
AND P.grade_id = G.grade_id
AND P.product_id = '${productId}'`;
connection.query(sql_get_product_info, function(error, result) {
if (error) {
console.log(error);
}
if (result.length !== 0) {
productInfo = result;
io.sockets.emit('productInfoLoaded', productInfo);
} else {
console.log('No Records Found')
}
});
});
// Load user types
socket.on('checkUserName', function(payload) {
var userName = payload.userName;
var sql_check_user_name =
`SELECT * from user_site_info
WHERE user_name = '${userName}'`;
connection.query(sql_check_user_name, function(error, result) {
if (error) {
console.log(error);
}
if (result.length !== 0) {
validUserName = false;
} else {
validUserName = true;
}
io.sockets.emit('userNameChecked', validUserName);
});
});
// socket.emit => emit events that are handled by the client
socket.emit('welcome', {
title: title,
flds: flds,
currentFld: currentFld,
fldDetails: fldDetails,
lfrSaved: lfrSaved,
userSiteInfoSaved: userSiteInfoSaved,
userList: userList,
userTypes: userTypes,
fldNumbers: fldNumbers,
productCodes: productCodes,
containerTypes: containerTypes,
areaCodes: areaCodes,
fldRows: fldRows,
fldInfo: fldInfo,
productInfo: productInfo,
weighInList: weighInList,
weighInNumbers: weighInNumbers,
weighInWeights: weighInWeights,
fldHeaderInfo: fldHeaderInfo,
weighInHeaderInfo: weighInHeaderInfo,
fldWeights: fldWeights,
userDeleted: userDeleted
});
connections.push(socket);
});
console.log(`Fishery Logistics is running at port ${ server.address().port }`);
You should definitely break this into several modules. Rule of thumb is to have controller modules and models.

Node.js - TypeError: Object #<Object> has no method

I am trying to include a module i found that will help manage users:
http://www.codeproject.com/Articles/382561/Session-Management-in-Nodejs
Ive copied the code and put it in the same directory as my server.js
I require it by doing:
var express = require('express');
var http = require('http'),
mysql = require("mysql");
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var sessionMgm = require("./sessionManagement");
Now in my socket i do this:
io.sockets.on('connection', function (socket) {
socket.on('setUserInfo', function (data) {
var sess = new Object();
sess.sessionId = socket.id;
sess.userId = data.userId;
sess.username = data.username;
sess.role = data.role;
sessionMgm.add(sess);
});
socket.on("private", function(data) {
if(data.agentName.length <= 0) {
data.agentName = 'Besökare';
}
io.sockets.in('Room_' + data.user_id).emit('updatechat', data.agentName, data.msg);
var user = sessionMgm.getSessionByUserId(data.id);
console.log('::: A socket with ID ' + user + ' connected! ::: ');
});
});
However i keep getting this error:
TypeError: Object # has no method 'getSessionByUserId'
Cant seem to figure out whats wrong, any ideas?
sessionManagement.js:
module.exports = sessionManagement;
var sessions = [];
//User roles list
var userRoles = {
Admin: "administrator",
User: "user",
Supervisor: "supervisor"
};
var sessionManagement = {
indexOf: function(sessionId) {
for(var i in sessions) {
if(sessions[i].sessionId == sessionId)
return i;
}
return null;
},
indexOfUser: function(userId) {
for(var i in sessions) {
if(sessions[i].userId == userId)
return i;
}
return null;
},
add: function(sessionData) {
sessions.push(sessionData);
},
remove: function(sessionId) {
var index = this.indexOf(sessionId);
if(index != null) {
sessions.splice(index, 1);
} else {
return null;
}
},
removeByUserId: function(userId) {
var index = this.indexOf(userId);
if(index != null) {
sessions.splice(index, 1);
} else {
return null;
}
},
getSessionById: function(userId) {
var index = this.indexOfUser(userId);
if(index != null) {
return sessions[index];
} else {
return null;
}
},
getSessionByUserId: function(sessionId) {
var index = this.indexOfUser(userId);
if(index != null) {
return sessions[index];
} else {
return null;
}
},
isAdmin: function(userId) {
var index = this.indexOfUser(userId);
if(index != null) {
if(users[index].role == userRoles.Admin) {
return true;
} else {
return false;
}
} else {
return null;
}
},
getUsersByRole: function(role) {
var usersByRole = [];
for(var i in users) {
if(users[i].role == role)
usersByRole.push(users[i]);
}
return usersByRole;
}
};
As madflow mentioned, you were missing module.exports = sessionManagement in sessionManagement.js
Then you got the error, because you were exporting sessionManagement, before initializing it. Moving the export line to the end of sessionManagement.js should fix that.
module.exports = sessionManagement; // <- you export here
...
...
...
var sessionManagement = { // and initialize here
Although sessionManagement declaration gets hoisted to the top of the module (and that's why you don't get Unexpected identifier or ReferenceError when assigning it to module.exports), it's initialization does not, so what really happens behind the scenes is something like that:
var sessionManagement; // undefined at this point
module.exports = sessionManagement; // <- you export here,
// but sessionManagement is undefined at this point
// and so will be module.exports after this line
...
...
...
sessionManagement = { // and initialize here

Resources