user: p1 IP: ::ffff:127.0.0.1 URL in node js - node.js

In my local setup of a node.js project I have a php page test.php. Now when in browser I put url http://localhost:8080/test.php I get the following error in console.
[12/28/2015 12:40:15] user: p1 IP: ::ffff:127.0.0.1 URL: /test.ph
Error requesting PHP backend (GET): Error: connect ECONNREFUSED.
Should I install some module of node js or it's a issue for my ubuntu version?
this is the whole code :
var http = require("http"),
https = require("https"),
mustache = require("mustache"),
fs = require("fs"),
pg = require("pg"),
url = require("url"),
crypto = require("crypto"),
serveStatic = require("serve-static"),
docxtemplater = require("docxtemplater"),
querystring = require("querystring"),
callstream = require("./callstream");
pg.defaults.poolSize = 25;
function log(text, req, stateObj) {
var u = (stateObj?stateObj.u:undefined),
ip = (req?req.connection.remoteAddress:undefined),
url = (req?req.url:undefined);
var d = new Date();
process.stderr.write("===============\n[" + (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + "] "
+ "user: " + (u||"(none)") + " IP: " + (ip||"(none)") + " URL: " + (url||"")
+ "\n" + text + "\n===============\n\n"
);
};
function validateToken(req) {
var rawCookie = req.headers.cookie;
if (!rawCookie) {return false;}
if (!rawCookie.length) {return false;}
var rawCookie = rawCookie.match(/t\=[A-Za-z0-9\+\/\=]+\.[A-Za-z0-9\+\/\=]+/);
if (!rawCookie) {return false;}
var parsedCookie = rawCookie[0].replace("t=", "").split(".");
if (parsedCookie[1] !== (crypto.createHash("sha256").update("sECr6eTt" + parsedCookie[0]).digest("base64"))) {return false;}
try {
var parsedPayload = JSON.parse((new Buffer(parsedCookie[0], "base64")).toString());
}
catch (e) {
return false;
}
if (!parsedPayload) {return false;}
var u = parseInt(parsedPayload.u),
m = (parseInt(parsedPayload.m)||0),
a = (parseInt(parsedPayload.a)||0);
if (!u) {return false;}
//if (!m) {return false;}
//if (!a) {return false;}
if ((new Date(parseInt(parsedPayload.t))).getDate() !== (new Date()).getDate()) {return false;}
if (parsedPayload.s !== crypto.createHash("sha256").update("true" + req.connection.remoteAddress + "s4CcrEEtT").digest("hex")) {return false;}
return {u:u, m:m, a:a};
};
function generateToken(req, u, m, a) {
var u = parseInt(u),
m = (parseInt(m)||0),
a = (parseInt(a)||0);
//if (!(u && m && a)) {log("token generation error");return "t=x";}
var rawPayload = {u:u, m:m, a:a, t:Date.now(), s:(crypto.createHash("sha256").update("true" + req.connection.remoteAddress + "s4CcrEEtT").digest("hex"))};
var encodedPayload = (new Buffer(JSON.stringify(rawPayload))).toString("base64");
var sig = crypto.createHash("sha256").update("sECr6eTt" + encodedPayload).digest("base64");
return encodedPayload + "." + sig;
};
function dbError(e, req, res, stateObj) {
log("DB Error: " + e, req, stateObj);
res.writeHead(500);
res.end();
};
function noRoute(req, res, stateObj) {
log("Bad Route: " + req.url, req, stateObj);
res.writeHead(404);
res.end();
};
function badParam(req, res, stateObj, pName, pVal) {
log("Bad GET Param: " + pName + " = " + pVal, req, stateObj);
res.writeHead(500);
res.end();
};
var static = serveStatic("../html/static");
var staticPub = serveStatic("../html/pub");
function serve(req, res) {
try {
if (req.method !== "GET" && req.method !== "POST") {
res.end();
return;
}
var parsedUrl = url.parse(req.url, true),
path = parsedUrl.pathname,
queryParams = parsedUrl.query,
stateObj = validateToken(req);
if (path == "/favicon.ico") {
res.writeHead(200, {'Content-Type': 'image/x-icon'});
res.write(favicon);
res.end();
return;
}
if (stateObj) {
// test.php url
var cReq = http.request({hostname:"localhost", port:8080, path:parsedUrl.path}, function(cRes) {
res.writeHead(200, cRes.headers);
cRes.pipe(res);
});
cReq.on("error", function(e) {
log("Error requesting PHP backend (GET): " + e, req, stateObj);
res.writeHead(500);
res.end();
});
cReq.end();
}
}
catch (e) {
log("Exception in primary request callback: " + e + "\n" + e.stack, req, stateObj)
res.writeHead(500);
res.end();
return;
}
};
http.createServer(serve).listen(8080);

Related

return value from callback function to send client response

I have a middleware that it should send the request to a function, wait for it to finish and send back to the client what that function returns. the problem is I dont figure it out how to return the value that I'm getting inside a cb, hence the response is always an empty array.
const insertMultiDoc = async function (req, res) {
const documents = await uploadMultipleFiles(userData, documentsList, index);
res.send(documents);
}
here is the middleware func simplified, so documents is always an empty array. I dont return correctly from the below function
const uploadMultipleFiles = function (userData, documentsList, index) {
let savedDoc;
let savedDocuments = [];
if (pathHelper.ensureDirectoryExistence(randomFilePath)) {
mv(documentsList[index].path, randomFilePath, async function (error) {
if ((userData.email !== undefined) && (userData.component !== undefined) && (userData.email != "") && (userData.component != "")) {
var tempFileFolderPath = pathHelper.createSpecificPath(userData.component, userData, uploadTime);
var randomFilePath = path.posix.normalize(tempFileFolderPath + "/" + generatedFileName);
var inputPath = randomFilePath + '.' + fileExt;
var outputFileFFmpeg720 = tempFileFolderPath + '/720p' + generatedFileName + '.' + fileExt;
var encodedFilePath = pathHelper.createDBPath(userData.component, userData) + "/720p" + generatedFileName + "." + fileExt;
var accessFilePath = pathHelper.createDBPath(userData.component, userData) + "/720p" + generatedFileName + "." + fileExt;
const output = await fileCompresser.compressFile(inputPath, outputFileFFmpeg720);
fileSize = await getSize(output);
newDoc = createNewDocumentObject(userData.senderId, userData.senderUsername, userData.email, userData.component, userData.sessionId, fileName, fileType, accessFilePath, encodedFilePath, null, fileSize, userData.parentComponent);
savedDoc = await documentController.createLocalDocument(newDoc);
fs.unlinkSync(inputPath);
index = index + 1;
console.log(savedDoc);
savedDocuments.push(savedDoc);
}
})
}
return savedDocuments;
}
for this situation I use q module
const q= require('q');
const uploadMultipleFiles = async function (userData, documentsList, index) {
let defer = q.defer(); // create a defer
try {
let savedDoc;
let savedDocuments = [];
if (pathHelper.ensureDirectoryExistence(randomFilePath)) {
mv(documentsList[index].path, randomFilePath, async function (error) {
if ((userData.email !== undefined) && (userData.component !== undefined) && (userData.email != "") && (userData.component != "")) {
var tempFileFolderPath = pathHelper.createSpecificPath(userData.component, userData, uploadTime);
var randomFilePath = path.posix.normalize(tempFileFolderPath + "/" + generatedFileName);
var inputPath = randomFilePath + '.' + fileExt;
var outputFileFFmpeg720 = tempFileFolderPath + '/720p' + generatedFileName + '.' + fileExt;
var encodedFilePath = pathHelper.createDBPath(userData.component, userData) + "/720p" + generatedFileName + "." + fileExt;
var accessFilePath = pathHelper.createDBPath(userData.component, userData) + "/720p" + generatedFileName + "." + fileExt;
const output = await fileCompresser.compressFile(inputPath, outputFileFFmpeg720);
fileSize = await getSize(output);
newDoc = createNewDocumentObject(userData.senderId, userData.senderUsername, userData.email, userData.component, userData.sessionId, fileName, fileType, accessFilePath, encodedFilePath, null, fileSize, userData.parentComponent);
savedDoc = await documentController.createLocalDocument(newDoc);
fs.unlinkSync(inputPath);
index = index + 1;
console.log(savedDoc);
savedDocuments.push(savedDoc);
}
})
}
defer.resolve(savedDocuments); // return result
} catch (error) {
defer.reject(error) // return error
}
return defer.promise; //return a promise
}
you can check the q documentation

NodeJS API: having trouble passing 2 parameters to request response

I am having trouble passing 2 ids via request response function. I can pass 1 id/argument without any issue but having trouble passing 2 arguments below is a snippet of my code:
server:
var http = require("http");
var org = require("../controllers/org");
var school = require("../controllers/school");
var academicSession = require("../controllers/academicSession");
var term = require("../controllers/term");
var gradingperiod = require("../controllers/gradingperiod");
var course = require("../controllers/course");
var stu = require("../controllers/student");
var cls = require("../controllers/class");
var user = require("../controllers/user");
var demo = require("../controllers/demographic");
var enroll = require("../controllers/enrollment");
var teach = require("../controllers/teacher");
var crscls = require("../controllers/schoolcs");
var enr = require("../controllers/enrollqrys");
var settings = require("../settings");
var httpMsgs = require("../core/httpMsgs");
http.createServer(function (req, resp) {
switch (req.method) {
case "GET":
if (req.url === "/") {
httpMsgs.showHome(req, resp);
}
else if (req.url === "/orgs") {
org.getOrgs(req, resp);
}
else if (req.url.match("/orgs/[0-9]+$")) {
var idorg = "[0-9]+";
var patt = new RegExp("/orgs/" + idorg);
if (patt.test(req.url)) {
patt = new RegExp(idorg);
var id = patt.exec(req.url);
org.getOrg(req, resp, id);
}
else {
httpMsgs.show404(req, resp);
}
}
***else if (req.url.match("/schools/[0-9]+[A-Za-z0-9\-\_]+/classes/[0-9]+[A-Za-z0-9\-\_]+/enrollments$")) {
var idcl = "[0-9]+[A-Za-z0-9\-\_]+";
var idsc = "[0-9]+[A-Za-z0-9\-\_]+";
var str = idcl + "[0-9]+[A-Za-z0-9\-\_]+" + idsc;
var patt = new RegExp("/schools/" + idcl + "/classes/" + idsc + "/enrollments");
if (patt.test(req.url)) {
patt = new RegExp(str);
var id = patt.exec(req.url);
enr.getEnrollmentsForClassInSchools(req, resp, id, arg2);
}
else {
httpMsgs.show404(req, resp);
}
}***
enrollqrys.js:
var db = require("../core/db");
var httpMsgs = require("../core/httpMsgs");
exports.getEnrollmentsForClassInSchools = function (req, resp, id, arg2) {
db.executeSql("EXEC dbo.getEnrollmentsForClassInSchools #clid = '" + id + "'" + ", #scid = '" + arg2 + "'", function (data, err) {
if (err) {
httpMsgs.show500(req, resp, err);
}
else {
//resp.writeHead(200, { "Content-Type": "application/json" });
//resp.write(JSON.stringify(data));
//resp.end();
httpMsgs.sendJson(req, resp, data);
}
});
};
exports.getStudentsForClassInSchool = function (req, resp, id, id) {
db.executeSql("EXEC dbo.getEnrollmentsForClassInSchools #clid = '" + clid + "'" + ", #scid =" + scid, function (data, err) {
if (err) {
httpMsgs.show500(req, resp, err);
}
else {
//resp.writeHead(200, { "Content-Type": "application/json" });
//resp.write(JSON.stringify(data));
//resp.end();
httpMsgs.sendJson(req, resp, data);
}
});
};
I get a not referenced error when testing this GET. Any help would be greatly appreciated. I will add that I am new to both javascript and nodejs
Error below:
Started listening at: 9000
C:\Users\THOMMA02\source\repos\NodejsConsoleApp1\NodejsConsoleApp1\core\server.js:281
enr.getEnrollmentsForClassInSchools(req, resp, id, arg2);
^
ReferenceError: arg2 is not defined
at Server. (C:\Users\THOMMA02\source\repos\NodejsConsoleApp1\NodejsConsoleApp1\core\server.js:281:72)
at emitTwo (events.js:126:13)
at Server.emit (events.js:214:7)
at parserOnIncoming (_http_server.js:619:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:112:17)
Waiting for the debugger to disconnect...

How to integrate soap xml API of unicommerce in nodejs

I am trying to hit xml Api of unicommerce by soap module in nodejs. It is working fine in soapUI.But is not integrated in node Application.
I am getting this error.
ERROR: {Error: Cannot parse response}.
var express = require("express");
var soap = require("soap");
var http = require('http');
var app = express();
var router = express.Router();
var username = "*********";
var password = "************";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");// not working
var wsdlUrl = 'https://lensclues.unicommerce.com/services/soap/uniware16.wsdl?facility=01';
const Autentication = '<soapenv:Header>' +
'<wsse:Security soapenv:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">' +
'<wsse:UsernameToken wsu:Id="UsernameToken-D6BE484999DA5E97D4148483888689316">' +
'<wsse:Username>**********</wsse:Username>' +
'<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">*******************</wsse:Password>'+
'<wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">$$$$$$$$$$$</wsse:Nonce>'+
'<wsu:Created>2017-01-19T15:14:46.893Z</wsu:Created>'+
'</wsse:UsernameToken>'+
'</wsse:Security>' +
'</soapenv:Header>'
soap.createClient(wsdlUrl, function (err, soapClient) {
soapClient.addSoapHeader(Autentication);
const data = '<soapenv:Envelope xmlns:ser="http://uniware.unicommerce.com /services/" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">' + '<soapenv:Body>' +
'<ser:GetInventorySnapshotRequest>' +
'<ser:ItemTypes>' +
'<ser:ItemType>' +
'<ser:ItemSKU>LCSGDB555xD15165S4PURx124</ser:ItemSKU>' +
'</ser:ItemType>' +
'</ser:ItemTypes>' +
'<ser:UpdatedSinceInMinutes>600</ser:UpdatedSinceInMinutes>' +
'</ser:GetInventorySnapshotRequest>' +
'</soapenv:Body>' +
'</soapenv:Envelope>'
if (err) {
console.log("err", err);
}
soapClient.GetInventorySnapshot({
data
}, function (err, result) {
if (err) {
console.log("ERROR:", err);
}
else {
console.log("result", result);
}
});
The question is: How do I send the request and print the answer?
Could you have any clues about this kind of issue?
Thanks a lot!
Try this send data xml format
xw = new XMLWriter;
xw.startDocument();
xw.startElement('soapenv:Envelope');
xw.writeAttribute('xmlns:ser', 'http://uniware.unicommerce.com/services/');
xw.writeAttribute('xmlns:soapenv', 'http://schemas.xmlsoap.org/soap/envelope/');
xw.startElement('soapenv:Header');
xw.startElement('wsse:Security');
xw.writeAttribute('soapenv:mustUnderstand', '1');
xw.writeAttribute('xmlns:wsse', 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd');
xw.startElement('wsse:UsernameToken');
xw.startElement('wsse:Username');
xw.text('******');
xw.endElement('wsse:Username');
xw.startElement('wsse:Password');
xw.text('*******password');
xw.endElement('wsse:Password');
xw.endElement('wsse:UsernameToken');
xw.endElement('wsse:Security');
xw.endElement('soapenv:Header');
xw.startElement('soapenv:Body');
xw.startElement('ser:GetInventorySnapshotRequest');
xw.startElement('ser:ItemTypes');
xw.startElement('ser:ItemType');
xw.startElement('ser:ItemSKU');
xw.text(sku);
xw.endDocument();
/*************************Request Module******************/
request(
{
'method': "POST",
'url': 'https://lensclues.unicommerce.com/services/soap/uniware16.wsdl?',
'body': xw.toString(),
'Content-Type': 'text/xml'
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
parseString(body, function (err, result) {
let tt = result['SOAP-ENV:Envelope']['SOAP-ENV:Body'][0]['GetInventorySnapshotResponse'][0]['Successful'][0]
console.log("Error---------->", tt);
console.log("Result---------->", result);
if (tt == "false") {
var check = result['SOAP-ENV:Envelope']['SOAP-ENV:Body'][0]['GetInventorySnapshotResponse'][0]['Errors'][0]['Error'][0];
console.log("check", check);
mainCallback(check, err);
}
else {
let inventoryValue = result['SOAP-ENV:Envelope']['SOAP-ENV:Body'][0]['GetInventorySnapshotResponse'][0]['InventorySnapshots'][0]["InventorySnapshot"][0]['Inventory'][0];
console.log("inventoryValue", inventoryValue);
if (inventoryValue >= prodQty) {
mainCallback(null, inventoryValue);
}
else {
mainCallback("Inventory not be available", err);
}
}
});
}
else {
console.log("------------->", error)
mainCallback("error in to fetch inventory data", error);
}
}
);

Paypal express checkout in Node.js (error 10410)

I have been unable to to successfully parse the returned token to authenticate final Paypal sandbox payment process. Any help or input would be greatly appreciated :)
REF:
https://github.com/petersirka/node-paypal-express-checkout
https://developer.paypal.com/docs/classic/express-checkout/in-context/integration/
Here is the error I am returned:
ACK: 'Failure',
VERSION: '52.0',
BUILD: '22708556'
L_ERRORCODE0: '10410',
L_SHORTMESSAGE0: 'Invalid token',
L_LONGMESSAGE0: 'Invalid token.',
L_SEVERITYCODE0: 'Error'
Client side:
<form id="myContainer" method="post" action="/api/payment/payone"></form>
<script>
window.paypalCheckoutReady = function () {
paypal.checkout.setup('XXX', {
environment: 'sandbox',
container: 'myContainer'
});
};
</script>
<script src="//www.paypalobjects.com/api/checkout.js" async></script>
API:
payone: function(req, res) {
var paypal = require('paypal-express-checkout').init('username', 'password', 'signature', 'return url', 'cancel url', 'debug');
paypal.pay('20130001', 10.00, 'XX', 'USD', false, function(err, url) {
if (err) {
console.log(err);
return;
}
res.redirect(url);
});
paypal.detail( "token", "PayerID", function(err, data, invoiceNumber, price) {
if (err) {
console.log(err);
return;
}
});
}
Finally, paypal-express doc:
var parser = require('url');
var https = require('https');
var qs = require('querystring');
function Paypal(username, password, signature, returnUrl, cancelUrl, debug) {
this.username = "XXX";
this.password = "XXX";
this.solutiontype = 'Mark';
this.signature = "XXX";
this.debug = debug || false;
this.returnUrl = 'XXX';
this.cancelUrl = 'XXX';
this.url = 'https://' + 'api-3t.sandbox.paypal.com' + '/nvp'; //'https://' + (debug ? 'api-3t.sandbox.paypal.com' : 'api-3t.paypal.com') + '/nvp';
this.redirect = 'https://' + 'www.sandbox.paypal.com/cgi-bin/webscr'; //https://' + (debug ? 'www.sandbox.paypal.com/cgi-bin/webscr' : 'www.paypal.com/cgi-bin/webscr');
};
Paypal.prototype.params = function() {
var self = this;
return {
USER: self.username,
PWD: self.password,
SIGNATURE: self.signature,
SOLUTIONTYPE: self.solutiontype,
VERSION: '52.0'
};
console.log(self);
};
Paypal.prototype.detail = function(token, payer, callback) {
if (token.get !== undefined && typeof(payer) === 'function') {
callback = payer;
payer = token.get.PayerID;
token = token.get.token;
}
console.log(token);
var self = this;
var params = self.params();
params.TOKEN = token;
params.METHOD = 'GetExpressCheckoutDetails';
self.request(self.url, 'POST', params, function(err, data) {
if (err) {
callback(err, data);
return;
}
if (typeof(data.CUSTOM) === 'undefined') {
callback(data, null);
return;
}
console.log('3.3');
var custom = data.CUSTOM.split('|');
var params = self.params();
params.PAYMENTACTION = 'Sale';
params.PAYERID = payer;
params.TOKEN = token;
params.AMT = custom[1];
params.CURRENCYCODE = custom[2];
params.METHOD = 'DoExpressCheckoutPayment';
self.request(self.url, 'POST', params, function(err, data) {
if (err) {
callback(err, data);
return;
}
console.log('3.4');
callback(null, data, custom[0], custom[1]);
});
});
return self;
};
Paypal.prototype.request = function(url, method, data, callback) {
var self = this;
var params = qs.stringify(data);
if (method === 'GET')
url += '?' + params;
var uri = parser.parse(url);
var headers = {};
headers['Content-Type'] = method === 'POST' ? 'application/x-www-form-urlencoded' : 'text/plain';
headers['Content-Length'] = params.length;
var location = '';
var options = { protocol: uri.protocol, auth: uri.auth, method: method || 'GET', hostname: uri.hostname, port: uri.port, path: uri.path, agent: false, headers: headers };
var response = function (res) {
var buffer = '';
res.on('data', function(chunk) {
buffer += chunk.toString('utf8');
})
req.setTimeout(exports.timeout, function() {
callback(new Error('timeout'), null);
});
res.on('end', function() {
var error = null;
var data = '';
if (res.statusCode > 200) {
error = new Error(res.statusCode);
data = buffer;
} else
data = qs.parse(buffer);
callback(error, data);
});
};
var req = https.request(options, response);
req.on('error', function(err) {
callback(err, null);
});
if (method === 'POST')
req.end(params);
else
req.end();
return self;
};
Paypal.prototype.pay = function(invoiceNumber, amount, description, currency, requireAddress, callback) {
// Backward compatibility
if (typeof(requireAddress) === 'function') {
callback = requireAddress;
requireAddress = false;
}
var self = this;
var params = self.params();
params.PAYMENTACTION = 'Sale';
params.AMT = prepareNumber(amount);
params.RETURNURL = self.returnUrl;
params.CANCELURL = self.cancelUrl;
params.DESC = description;
params.NOSHIPPING = requireAddress ? 0 : 1;
params.ALLOWNOTE = 1;
params.CURRENCYCODE = currency;
params.METHOD = 'SetExpressCheckout';
params.INVNUM = invoiceNumber;
params.CUSTOM = invoiceNumber + '|' + params.AMT + '|' + currency;
self.request(self.url, 'POST', params, function(err, data) {
if (err) {
callback(err, null);
return;
}
if (data.ACK === 'Success') {
callback(null, self.redirect + '?cmd=_express- checkout&useraction=commit&token=' + data.TOKEN);
return;
}
callback(new Error('ACK ' + data.ACK + ': ' + data.L_LONGMESSAGE0), null);
});
return self;
console.log(self);
};
function prepareNumber(num, doubleZero) {
var str = num.toString().replace(',', '.');
var index = str.indexOf('.');
if (index > -1) {
var len = str.substring(index + 1).length;
if (len === 1)
str += '0';
if (len > 2)
str = str.substring(0, index + 3);
} else {
if (doubleZero || true)
str += '.00';
}
return str;
};
exports.timeout = 10000;
exports.Paypal = Paypal;
exports.init = function(username, password, signature, returnUrl, cancelUrl, debug) {
return new Paypal(username, password, signature, returnUrl, cancelUrl, debug);
};
exports.create = function(username, password, signature, returnUrl, cancelUrl, debug) {
return exports.init(username, password, signature, returnUrl, cancelUrl, debug);
};
Usually we encounter Error 10410 if there is incorrect token or no token passed.
please make sure that you are passing the right PayPal Express token.
for information on error codes you may refer: https://developer.paypal.com/docs/classic/api/errorcodes/

TypeError: Cannot read property 'emails' of null

Here is line 54, where I am getting the error:
if (docr.emails) {
And here is the rest of my original code:
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var config = require('./config'),
xlsx = require('./xlsx'),
utils = require('./utils'),
_ = require('lodash'),
url = config.DB_URL;
var meetings = [];
function findNumberOfNotesByMeeting(db, meeting, callback) {
var meetingId = meeting._id.toString(),
meetingName = meeting.name.displayValue,
attendees = meeting.attendees;
host = meeting.host;
var count = 1, pending = 0, accepted = 0;
console.log("==== Meeting: " + meetingName + '====');
_.each(attendees, function(item) {
console.log(count++ + ': ' + item.email + ' (' + item.invitationStatus + ')');
if (item.invitationStatus == 'pending') { pending++; }
else if (item.invitationStatus == 'accepted') { accepted++; }
});
console.log("*** " + attendees.length + ", " + pending + "," + accepted);
db.collection('users').findOne({'_id': new ObjectId(host)}, function(err, doc) {
var emails = [];
if (doc.emails) {
doc.emails.forEach(function(e) {
emails.push(e.email + (e.primary ? '(P)' : ''));
});
}
var email = emails.join(', ');
if (utils.toSkipEmail(email)) {
callback();
} else {
db.collection('notes').find({ 'meetingId': meetingId }).count(function(err, count) {
if (count != 0) {
console.log(meetingName + ': ' + count + ',' + attendees.length + ' (' + email + ')');
meetings.push([ meetingName, count, email, attendees.length, pending, accepted ]);
}
callback();
});
}
});
}
function findMeetings(db, meeting, callback) {
var host = meeting.host;
db.collection('users').findOne({'_id': new ObjectId(host)}, function(err, docr) {
var emails = [];
if (docr.emails) {
docr.emails.forEach(function(e) {
emails.push(e.email + (e.primary ? '(P)' : ''));
});
}
var email = emails.join(', ');
if (utils.toSkipEmail(email)) {
callback();
} else {
var cursor = db.collection('meetings').find({
'email': {'$regex': 'abc', '$options': 'i' }
});
}
cursor.count(function(err, count) {
console.log('count: ' + count);
var cnt = 0;
cursor.each(function(err, doc) {
assert.equal(err, null);
if (doc != null) {
findNumberOfNotesByMeeting(db, doc, function() {
cnt++;
if (cnt >= count) { callback(); }
});
}
});
});
});
};
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
findMeetings(db, function() {
var newMeetings = meetings.sort(function(m1, m2) { return m2[1] - m1[1]; });
newMeetings.splice(0, 0, [ 'Meeting Name', 'Number of Notes', 'Emails' ]);
xlsx.writeXLSX(newMeetings, config.xlsxFileNameMeetings);
db.close();
});
});
Try the following:
function findMeetings(db, meeting, callback) {
var host = meeting.host;
db.collection('users').findOne({'_id': new ObjectId(host)}, function(err, docr) {
var emails = [];
if (!err && docr && docr.emails) {
docr.emails.forEach(function(e) {
emails.push(e.email + (e.primary ? '(P)' : ''));
});
}
...

Resources