How do we get the Edit id of the corresponding node - getorgchart

I am trying to edit the GetOrgChart node by pointing it to a url which needs the id of the corresponding node to work. I am stuck here and would like the solution out. My code is as follows
getOrgChart.themes.monica.box += '<g transform="matrix(1,0,0,1,350,10)">'
+ btnAdd
+ btnEdit
+ btnDel
+ '</g>';
var orgChart = new getOrgChart(chartElement, {
scale: 0.5,
theme: "monica",
primaryFields: resp2.primaryFields,
photoFields: [resp2.photoField],
enableZoom: true,
enableEdit: true,
enableDetailsView: true,
dataSource: processed
});
function getNodeByClickedBtn(el) {
while (el.parentNode) {
el = el.parentNode;
if (el.getAttribute("data-node-id"))
return el;
}
return null;
}
var init = function () {
var btns = document.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function () {
var nodeElement = getNodeByClickedBtn(this);
var action = this.getAttribute("data-action");
var id = nodeElement.getAttribute("data-node-id");
var node = orgChart.nodes[id];
switch (action) {
case "add":
window.location.href='${request.contextPath}' + resp2.addLink;
break;
case "edit":
//console.log('&id=' + processed['id']);
// return;
window.location.href='${request.contextPath}' + resp2.editLink + '&id=' + resp.data[]['id'];
break;
case "delete":
window.location.href='${request.contextPath}' + resp2.deleteLink;
break;
}
});
}
}
init();
},
error: function (ex) {
console.log(ex);
}
});
},
error: function (ex) {
console.log(ex);
}
});
The problem code is here
case "edit":
//console.log('&id=' + processed['id']);
// return;
window.location.href='${request.contextPath}' + resp2.editLink + '&id=' + resp.data[]['id'];
break;
What should I do to access the id in the resp.data[index] variable?

I got my answer. The example extracted variables and id of the node was one of them.
var nodeElement = getNodeByClickedBtn(this);
var action = this.getAttribute("data-action");
var id = nodeElement.getAttribute("data-node-id");
var node = orgChart.nodes[id];

Related

How do I add an inline HTML field to a Suitelet to hold html markup?

Edit: code updated
I am trying to follow along with this blogpost which shows how to create a Suitelet which has a formatted table https://followingnetsuite.com/2020/10/16/skip-freemarker-by-delivering-saved-search-results-in-a-suitelet/
The blog post references adding a inline html field to hold the html mark up. I have tried to add this to the code though I know I am way off:
/**
*#NApiVersion 2.x
*#NScriptType Suitelet
*/
define(["N/search", "N/ui/serverWidget"], function (search, ui) {
function onRequest(context) {
if (context.request.method === "GET") {
var form = ui.createForm({ title: "freemarker test" });
function getIssues() {
var issues = new Array();
var mySearch = search.load({
id: "customsearchcustomerallview",
});
var myPages = mySearch.runPaged({ pageSize: 1000 });
for (var i = 0; i < myPages.pageRanges.length; i++) {
var myPage = myPages.fetch({ index: i });
myPage.data.forEach(function (result) {
var issue = {};
mySearch.columns.forEach(function (col, index) {
issue["column_" + index] = {
label: col.label,
text: result.getText(col),
value: result.getValue(col),
};
});
issues.push(issue);
});
}
return issues;
}
function formatIssues(issues) {
var html = new Array();
html.push('<table class="RPT">');
html.push("<thead>");
if (issues.length > 0) {
var issue = issues[0];
html.push("<tr>");
for (var i = 0; i < 20; i++) {
if (issue.hasOwnProperty("column_" + i)) {
var sortType = isNaN(
issue["column_" + i].text || issue["column_" + i].value
)
? "string"
: "float";
html.push(
'<th data-sort="' +
sortType +
'">' +
issue["column_" + i].label +
"</th>"
);
}
}
html.push("</tr>");
}
html.push("</thead>");
html.push("<tbody>");
issues.forEach(function (issue) {
html.push("<tr>");
for (var i = 0; i < 20; i++) {
if (issue.hasOwnProperty("column_" + i)) {
var vAlign = isNaN(
issue["column_" + i].text || issue["column_" + i].value
)
? "left"
: "right";
html.push(
'<td align="' +
vAlign +
'">' +
(issue["column_" + i].text || issue["column_" + i].value) +
"</td>"
);
} else {
break;
}
}
html.push("</tr>");
});
html.push("</tbody>");
html.push("</table>");
return html.join("\n");
}
var htmlField = html.addField({
id: "custpage_html",
label: "html",
type: ui.FieldType.INLINEHTML,
});
htmlField.defaultValue = formatIssues(getIssues());
context.response.writePage(form);
}
}
return {
onRequest: onRequest,
};
});
I can't see the correct way to add this though. Where do I add the inline html field?
For a Suitelet, does the 'context.response.writePage(form)' need to be at the end of the rest of the code? (i.e. after the function that relates to the html markup?
Thanks
Add your HTML via the defaultValue property of the Inline HTML Field.
Structure your script as follows:
/**
*#NApiVersion 2.x
*#NScriptType Suitelet
*/
define(["N/search", "N/ui/serverWidget"], function (search, ui) {
function onRequest(context) {
if (context.request.method === "GET") {
var form = ui.createForm({ title: "freemarker test" });
function getIssues() {
var issues = [];
return issues;
}
function formatIssues(issues) {
var html = [];
return html.join("\n");
}
var htmlField = form.addField({
id: "custpage_html",
label: "html",
type: ui.FieldType.INLINEHTML,
});
htmlField.defaultValue = formatIssues(getIssues());
context.response.writePage(form);
}
}
return {
onRequest: onRequest,
};
});
or, if you don't need any other NetSuite Form elements:
/**
*#NApiVersion 2.x
*#NScriptType Suitelet
*/
define(["N/search"], function (search) {
function onRequest(context) {
if (context.request.method === "GET") {
function getIssues() {
var issues = [];
return issues;
}
function formatIssues(issues) {
var html = [];
return html.join("\n");
}
context.response.write(formatIssues(getIssues()));
}
}
return {
onRequest: onRequest,
};
});
You add the field to your form by calling Form.addField from your form object:
var field = html.addField({
id : 'custpage_inlineresults',
type : serverWidget.FieldType.INLINEHTML,
label : 'Search Results'
});
See SuiteAnswer #43669.

Apply the same JavaScript on multiple div scroll

I found this simple horizontal scroll :
http://jsfiddle.net/Lpjj3n1e/
Its working fine, but if I duplicate the horizontal scroll, only the first scroll function well.
What can I do to the JavaScript to be applied on 2, 3 or any variable number of generated scrolls ?
$(function() {
var print = function(msg) {
alert(msg);
};
var setInvisible = function(elem) {
elem.css('visibility', 'hidden');
};
var setVisible = function(elem) {
elem.css('visibility', 'visible');
};
var elem = $("#elem");
var items = elem.children();
// Inserting Buttons
elem.prepend('<div id="right-button" style="visibility: hidden;"><</div>');
elem.append(' <div id="left-button">></div>');
// Inserting Inner
items.wrapAll('<div id="inner" />');
// Inserting Outer
debugger;
elem.find('#inner').wrap('<div id="outer"/>');
var outer = $('#outer');
var updateUI = function() {
var maxWidth = outer.outerWidth(true);
var actualWidth = 0;
$.each($('#inner >'), function(i, item) {
actualWidth += $(item).outerWidth(true);
});
if (actualWidth <= maxWidth) {
setVisible($('#left-button'));
}
};
updateUI();
$('#right-button').click(function() {
var leftPos = outer.scrollLeft();
outer.animate({
scrollLeft: leftPos - 200
}, 800, function() {
debugger;
if ($('#outer').scrollLeft() <= 0) {
setInvisible($('#right-button'));
}
});
});
$('#left-button').click(function() {
setVisible($('#right-button'));
var leftPos = outer.scrollLeft();
outer.animate({
scrollLeft: leftPos + 200
}, 800);
});
$(window).resize(function() {
updateUI();
});
});

how to create multiple it statements with in one For loop protractor

I have multiple it statements in one describe {}. In one it statement I am reading data from excel and doing for loop to execute test scripts for number of users in the sheet. I need to create page model and so for each page thinking on creating one it statement. How can we do that. Here is my actual script
var login = require('./login');
var utility = require('./utility');
var exRead = require('./readExcel');
describe('MSIX Smoke', function () {
var userList = [];
beforeAll(function(done) {
browser.get('https://url'); //Dev url
expect(browser.getTitle()).toEqual('test');
exRead().then(function(excelData) {
userList = prepData(excelData);
done();
});
});
it('should login users', function() {
var loopCount = userList.length
loopCount=1;
for (var i = 0; i<loopCount; i++) {
var data = userList[i];
loginScript(data[0], data[1], data[2]);
login.clickSignOut();
}
})
it('search for a student', function () {
console.log(data[3]);
});
it ('click on my account', function () {
//some code
})
});
function prepData(data) {
var formattedData = [];
var counter = data.length / 5;
for (var i = 0; i < counter; i++) {
formattedData.push(data.splice(0,5))
}
return formattedData;
}
function loginScript(username, password, userType) {
var loginName = element(by.css('.nameP'));
console.log(username, password);
login.fillUsername(username);
login.fillPassword(password);
login.clickSignup();
login.clickPrivacy();
console.log("User " + username + " with user type "+userType+" logged in successfully");
loginName.isPresent;
utility.getStringText("Logged in user name is: ", loginName);
return loginName;
};
Give code examples with two approaches:
describe('xxx', function() {
browser.get('https://www.npmjs.com');
var datas = [1, 2, 3];
// Option 1, use for loop and javascript closure
for (var i = 0, len = datas.length; i < len; i++) {
(function(i) {
return it('yyy ' + i, function() {
console.log('data[' + i + '] = ' + datas[i]);
browser.getTitle().then(function(title) {
console.log('title[' + i + '] = ' + title);
});
});
})(i);
}
// option 2, use Array.forEach()
datas.forEach(function(data, i) {
it('yyy ' + i, function() {
console.log('data[' + i + '] = ' + data);
browser.getTitle().then(function(title) {
console.log('title[' + i + '] = ' + title);
});
});
})
});

nodejs async how to set callback

I have the following piece of code which is working fine.
var config = require('./config');
var cheerio = require('cheerio');
var myhttp = require('./myHttp');
var stringHelper = require('./stringHelper');
var Base64 = require('./base64.js').Base64;
var Encrypt = require('./Encrypt.js');
var myEncode = require('./Encode.js');
var rules = require('./rules');
var io = require('socket.io-emitter')({ host: '127.0.0.1', port: 6379 });
var mysql = require('mysql');
delete require.cache[require.resolve('./requestLogin1.js')]
var myvar = require('./requestLogin1.js');
var connection = mysql.createConnection(
{
host : 'localhost',
user : 'root',
password : 'abc',
database : 'abcd'
}
);
connection.connect(function(err) {
if (err) {
console.log('error connecting: ' + err.stack);
return;
}
});
var timerOB;
var timerMW;
var timerP;
var timerTL;
var news = {
'mw': [],
'ob': [],
'all': {},
};
var status = false;
function round(rnum, rlength) {
return newnumber = Math.round(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
}
function roundup(rnum, rlength) {
return newnumber = Math.ceil(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
}
function rounddown(rnum, rlength) {
return newnumber = Math.floor(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
}
function function1(_html) {
console.log('function1 run')
var $ = cheerio.load(_html);
var v_lgnid = $('#userId').attr('value');
var v_psswrd = config.password;
var v_data = v_lgnid + "|" + v_psswrd;
var _key = $('#accntid').attr('value');
if (_key) {
v_data = Base64.encode(Encrypt.AESEncryptCtr(v_data, _key , "256"));
v_data = escape(v_data);
myhttp.get(
'https://example.com/ValidPassword.jsp?' + $('#name').attr('value') + "=" + v_data,
function (_htmlShowImage) {
if (_htmlShowImage && _htmlShowImage.trim() == "OK") {
function2();
} else {
console.log('Login Fail');
}
});
} else {
login();
console.log('Encrypt password error');
}
}
function function2() {
myhttp.get(
'https://example.com/QuestionsAuth.jsp',
function (_htmlShowImage) {
var $ = cheerio.load(_htmlShowImage);
var sLoginID = $('#sLoginID').attr('value');
var Answer1 = config.answer1;
var Answer2 = config.answer2;
var Index1 = $('#st1').attr('value');
var Index2 = $('#st2').attr('value');
var v_data = sLoginID + "|" + Answer1 + "|" + Answer2 + "|" + Index1 + "|" + Index2;
v_data = Base64.encode(Encrypt.AESEncryptCtr(v_data, $('#key_questauth').attr('value'), "256"));
v_data = escape(v_data);
myhttp.get(
'https://example.com/ValidAnswers.jsp?' + $('#name_questauth').attr('value') + "=" + v_data,
function (_htmlShowImage) {
if (_htmlShowImage && _htmlShowImage.trim() == "OK") {
//rootCallback();
myhttp.get(
'https://example.com/DefaultLogin.jsp',
function (_html) {
console.log('Login sucess')
stringHelper.SaveFileCookies('abcd.txt', myhttp.loadCookie(), 'save cookie login sucess');
if (timerMW) {
clearTimeout(timerMW);
}
timerMW = setTimeout(function6, config.DelayExtractMW);
if (timerOB) {
clearTimeout(timerOB);
}
timerOB = setTimeout(function5, config.DelayExtractOB);
if (timerP) {
clearTimeout(timerP);
}
timerP = setTimeout(function4, config.function4);
});
} else {
console.log('Login Fail - timer');
}
});
});
}
var login = function () {
if (timerMW) {
clearTimeout(timerMW);
}
if (timerOB) {
clearTimeout(timerOB);
}
if (timerP) {
clearTimeout(timerP);
}
if (timerTL) {
clearTimeout(timerTL);
}
myhttp.init();
myhttp.post(
'https://example.com/ShowImage.jsp',
{ "requiredLogin": myEncode.Convert(config.uname) },
function (_htmlpost) {
if (_htmlpost) {
function1(_htmlpost);
} else {
if (timerTL) {
clearTimeout(timerTL);
}
timerTL = setTimeout(login, config.DelayNestError);
}
});
}
exports.login = login;
function function3() {
return {
TS: '',
MWP: 0,
LTP: 0,
NQ: 0,
OBBP: '',
OBSP: '',
CurrTime: 0,
rules: {}
};
}
function function4() {
status = false;
myhttp.get('https://example.com/PB.jsp?Exchange=',
function (_html) {
if (_html && _html.length > 10) {
news.pn = {};
$ = cheerio.load(_html);
$('tr[id^="TR"]').each(function () {
status = true;
var symbol = $('td:nth-child(3)', this).text().trim();
var objob = {
'NQ': parseInt($('td:nth-child(11)', this).text().trim()),
};
var post = {
'symbol': symbol,
'nq': objob.NQ
};
connection.query('INSERT INTO NP SET ?', post, function (err,result){
if (err)
{console.log("NP sql insert error : " +symbol);}
else {
console.log("data inserted into NP Table : " +symbol);
}
});
var objstock = news.all[symbol];
if (typeof objstock!='undefined') {
objstock.NQ = objob.NQ;
news.pn[symbol] = objob;
news.all[symbol] = objstock;
if (status) {
io.emit('news', news);
}
}
else
{
console.log('symbol not found');
}
});
if (timerP) {
clearTimeout(timerP);
}
console.log('setTimer function4:' + config.DelayExtractPn);
timerP = setTimeout(function4, config.DelayExtractPn);
}
connection.query('UPDATE MASTER1 SET tbq = (SELECT sum(a.bq) FROM (select distinct symbol, bq from NP) as a)', function (err,result){
if (err)
{console.log("CQ06 skipped: ");}
else {
console.log("Step 6 - Master1 tbq data updated");
}
});
connection.query('UPDATE MASTER1 SET tsq = (SELECT sum(a.sq) FROM (select distinct symbol, sq from NP) as a)', function (err,result){
if (err)
{console.log("CQ07 skipped: ");}
else {
console.log("Step 7 - Master1 tsq data updated");
}
});
});
}
function function5() {
status = false;
myhttp.get('https://example.com/OB.jsp?Exchange=&OrderType=All',
function (_html) {
if (_html && _html.length > 10) {
$ = cheerio.load(_html);
console.log('OB - Step 2 - html loaded for parsing');
news.ob = [];
$('tr[id^="TR"]').each(function () {
var statusOrder = $('td:nth-child(20)', this).text().trim();
if (statusOrder.toLowerCase().indexOf('open') >= 0) {
status = true;
var objob = {
'symbol': $('td:nth-child(6)', this).text().trim(),
'buysell': $('td:nth-child(9)', this).text().trim(),
'ordernumber': $('input[name="Select"]', this).attr('value'),
};
var objstock = news.all[objob.symbol];
objstock.OBBP = objob.buysell == "BUY"?objob.ordernumber:"";
objstock.OBSP = objob.buysell == "SELL"?objob.ordernumber:"";
news.ob.push(objob);
}
});
if (status) {
io.emit('news', news);
}
if (timerOB) {
clearTimeout(timerOB);
}
timerOB = setTimeout(function5, config.DelayExtractOB);
}
});
}
function function6() {
myhttp.get(
'https://example.com/MW.jsp?',
function (_html) {
if (_html && _html.length > 10) {
var $ = cheerio.load(_html);
status = false;
news.mw = [];
var countCheckRule = 0;
var countCheckedRule = 0;
var tmpall = {};
$('tr[onclick]').each(function () {
status = true;
var data1 = $("input[onclick*='Apply(']", this).attr('onclick');
var arrdata1 = data1.split("','");
var stockid = arrdata1[1].split('|')[0];
var symbol = $('td:nth-child(3)', this).text().trim();
var price = parseFloat($('td:nth-child(4)', this).text().trim());
var cTime = stringHelper.getIndiaTime();
var CurrTime = cTime.toLocaleTimeString();//(will be updated every 60 seconds)
news.mw.push({
'symbol': symbol,
'price': price,
'stockid': stockid,
'CurrTime': CurrTime,
});
var objstock = news.all[symbol];
if (!objstock) {
objstock = function3();
}
if (!news.pn[symbol]) {
objstock.NQ = 0;
}
var notfoundob = true;
for (var symbolkey in news.ob) {
if (news.ob[symbolkey].symbol == symbol) {
notfoundob = false;
}
}
if (notfoundob) {
objstock.OBBP = "";
objstock.OBSP = "";
}
objstock.TS = symbol;//trade symbol
objstock.MWP = stockid;//trade id
objstock.LTP = price;
objstock.CurrTime = CurrTime;
rules.checRules(objstock, myhttp, function (rules_res) {
objstock.rules = rules_res;
tmpall[symbol] = objstock;
});
countCheckRule++;
});
rules.rule12(tmpall, function (_tmpall) {
tmpall = _tmpall;
});
news.all = tmpall;
if (!status) {
login();
console.log('MW - Step 9 - logged out');
} else {
io.emit('news', news);
if (timerMW) {
clearTimeout(timerMW);
}
timerMW = setTimeout(function6, config.DelayExtractMW);
}
} else {
if (timerMW) {
clearTimeout(timerMW);
}
timerMW = setTimeout(function6, config.DelayExtractMW);
}
});
}
Now i want to use async to ensure that function6 is run only after function4 & function5 is run.
I have tried to learn about async from various forums and have changed the code as follows:
var async = require('async'); //line added
// change made
async.parallel([
function function4(callback) {
status = false;
myhttp.get('https://example.com/PB.jsp?Exchange=',
function (_html) {
if (_html && _html.length > 10) {
news.pn = {};
$ = cheerio.load(_html);
$('tr[id^="TR"]').each(function () {
status = true;
var symbol = $('td:nth-child(3)', this).text().trim();
var objob = {
'NQ': parseInt($('td:nth-child(11)', this).text().trim()),
};
console.log('Posn - Step 3A - Found position:' + symbol);
var post = {
'symbol': symbol,
'nq': objob.NQ
};
connection.query('INSERT INTO NP SET ?', post, function (err,result){
if (err)
{console.log("NP sql insert error : " +symbol);}
else {
console.log("data inserted into NP Table : " +symbol);
}
});
var objstock = news.all[symbol];
if (typeof objstock!='undefined') {
objstock.NQ = objob.NQ;
news.pn[symbol] = objob;
news.all[symbol] = objstock;
if (status) {
io.emit('news', news);
}
}
else
{
console.log('symbol not found');
}
});
if (timerP) {
clearTimeout(timerP);
}
console.log('setTimer function4:' + config.DelayExtractPn);
timerP = setTimeout(function4, config.DelayExtractPn);
}
connection.query('UPDATE MASTER1 SET tbq = (SELECT sum(a.bq) FROM (select distinct symbol, bq from NP) as a)', function (err,result){
if (err)
{console.log("CQ06 skipped: ");}
else {
console.log("Step 6 - Master1 tbq data updated");
}
});
connection.query('UPDATE MASTER1 SET tsq = (SELECT sum(a.sq) FROM (select distinct symbol, sq from NP) as a)', function (err,result){
if (err)
{console.log("CQ07 skipped: ");}
else {
console.log("Step 7 - Master1 tsq data updated");
}
});
callback(); //line added
});
},
function function5(callback) {
status = false;
myhttp.get('https://example.com/OB.jsp?Exchange=&OrderType=All',
function (_html) {
if (_html && _html.length > 10) {
$ = cheerio.load(_html);
console.log('OB - Step 2 - html loaded for parsing');
news.ob = [];
$('tr[id^="TR"]').each(function () {
var statusOrder = $('td:nth-child(20)', this).text().trim();
if (statusOrder.toLowerCase().indexOf('open') >= 0 || statusOrder.toLowerCase().indexOf('trigger pending') >= 0) {
status = true;
var objob = {
'symbol': $('td:nth-child(6)', this).text().trim(),
'buysell': $('td:nth-child(9)', this).text().trim(),
'ordernumber': $('input[name="Select"]', this).attr('value'),
};
var objstock = news.all[objob.symbol];
objstock.OBBP = objob.buysell == "BUY"?objob.ordernumber:"";
objstock.OBSP = objob.buysell == "SELL"?objob.ordernumber:"";
news.ob.push(objob);
}
});
if (status) {
console.log('OB - Step 5 - pushed to html page');
io.emit('news', news);
}
if (timerOB) {
clearTimeout(timerOB);
}
timerOB = setTimeout(function5, config.DelayExtractOB);
}
callback(); //line added
});
}
],
function function6() {
myhttp.get(
'https://example.com/MW.jsp?',
function (_html) {
if (_html && _html.length > 10) {
var $ = cheerio.load(_html);
status = false;
news.mw = [];
var countCheckRule = 0;
var countCheckedRule = 0;
var tmpall = {};
$('tr[onclick]').each(function () {
status = true;
var data1 = $("input[onclick*='Apply(']", this).attr('onclick');
var arrdata1 = data1.split("','");
var stockid = arrdata1[1].split('|')[0];
var symbol = $('td:nth-child(3)', this).text().trim();
var price = parseFloat($('td:nth-child(4)', this).text().trim());
var cTime = stringHelper.getIndiaTime();
var CurrTime = cTime.toLocaleTimeString();//(will be updated every 60 seconds)
news.mw.push({
'symbol': symbol,
'price': price,
'stockid': stockid,
'CurrTime': CurrTime,
});
var objstock = news.all[symbol];
if (!objstock) {
objstock = function3();
}
if (!news.pn[symbol]) {
objstock.NQ = 0;
}
var notfoundob = true;
for (var symbolkey in news.ob) {
if (news.ob[symbolkey].symbol == symbol) {
notfoundob = false;
}
}
if (notfoundob) {
objstock.OBBP = "";
objstock.OBSP = "";
}
objstock.TS = symbol;//trade symbol
objstock.MWP = stockid;//trade id
objstock.LTP = price;
objstock.CurrTime = CurrTime;
rules.checRules(objstock, myhttp, function (rules_res) {
objstock.rules = rules_res;
tmpall[symbol] = objstock;
});
countCheckRule++;
});
//new check rules
rules.rule12(tmpall, function (_tmpall) {
tmpall = _tmpall;
});
news.all = tmpall;
if (!status) {
login();
} else {
io.emit('news', news);
if (timerMW) {
clearTimeout(timerMW);
}
timerMW = setTimeout(function6, config.DelayExtractMW);
}
} else {
if (timerMW) {
clearTimeout(timerMW);
}
timerMW = setTimeout(function6, config.DelayExtractMW);
}
});
});
Since my original functions do not have any callback, and since async needs callback, i have tried to code a callback in function4 & function5 - but I guess i have not coded it correctly.
I am getting an error in the line where callback is present that states "TypeError: undefined is not a function".
How do i correct this?
Related Question No. 2 : the current code has a timer function whereby function4, function5 and function6 runs with a preset timer. If async works, how do i define a timer whereby the combined set of function4,5 & 6 works based on a preset timer?
Sorry about the long code -- i am new to nodejs and was handed over this code as such and am trying to get this change made.
Thanks for your guidance.
You can instead make function4 and function5 to return promise and then execute function6 only after both function4's and function5's promise gets resolved.

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