TypeError in Node.js application - node.js

I've copied this example program from Node.js textbook:
var MongoClient = require('mongodb').MongoClient;
var website = {
url: 'http://www.google.com',
visits: 0
};
var findKey = {
url: 'www.google.com'
}
MongoClient.connect('mongodb://127.0.0.1:27017/demo', { useNewUrlParser: true }, function(err, client) {
var db = client.db('demo');
if(err) throw err;
var collection = db.collection('websites');
collection.insert(website, function(err, docs) {
var done = 0;
function onDone(err) {
done++;
if(done < 4) return;
collection.find(findKey).toArray(function(err, results) {
console.log('Visits:', results[0].visits);
//cleanup
collection.drop(function() {
client.close();
});
});
}
var incrementVisits = {
'$inc': {
'visits': 1
}
};
collection.update(findKey, incrementVisits, onDone);
collection.update(findKey, incrementVisits, onDone);
collection.update(findKey, incrementVisits, onDone);
collection.update(findKey, incrementVisits, onDone);
});
});
It throws this error when I run it:
/Users/me/Documents/Beginning NodeJS/node_modules/mongodb/lib/utils.js:132
throw err;
^
TypeError: Cannot read property 'visits' of undefined
at /Users/me/Documents/Beginning NodeJS/update/2update.js:26:43
at result (/Users/me/Documents/Beginning NodeJS/node_modules/mongodb/lib/utils.js:414:17)
at executeCallback (/Users/me/Documents/Beginning NodeJS/node_modules/mongodb/lib/utils.js:406:9)
at handleCallback (/Users/me/Documents/Beginning NodeJS/node_modules/mongodb/lib/utils.js:128:55)
at self.close (/Users/me/Documents/Beginning NodeJS/node_modules/mongodb/lib/cursor.js:905:60)
at handleCallback (/Users/me/Documents/Beginning NodeJS/node_modules/mongodb/lib/utils.js:128:55)
at completeClose (/Users/me/Documents/Beginning NodeJS/node_modules/mongodb/lib/cursor.js:1044:14)
at Cursor.close (/Users/me/Documents/Beginning NodeJS/node_modules/mongodb/lib/cursor.js:1057:10)
at /Users/me/Documents/Beginning NodeJS/node_modules/mongodb/lib/cursor.js:905:21
at handleCallback (/Users/me/Documents/Beginning NodeJS/node_modules/mongodb-core/lib/cursor.js:199:5)
I can't see whats wrong here but the textbook is a few years old and I've already had issues where the code was out of date and wouldn't work so I want to check if that is the case here.

It's a pretty horrible example you are following, but basically there are errors there essentially compounded from http:///www.google.com which is created as the value in the document is different to www.google.com, therefore you don't get a result and it's undefined when trying to read a property from an empty array.
The basic corrections would be to fix that, and actually use findOneAndUpdate() in all cases, since that will atomically return a document.
var MongoClient = require('mongodb').MongoClient;
var website = {
url: 'http://www.google.com',
visits: 0
};
var findKey = {
url: 'http://www.google.com'
}
MongoClient.connect('mongodb://127.0.0.1:27017/demo', { useNewUrlParser: true }, function(err, client) {
var db = client.db('demo');
if(err) throw err;
var collection = db.collection('websites');
collection.findOneAndUpdate(
findKey, website, { upsert: true },function(err, doc) {
var done = 0;
function onDone(err,doc) {
done++;
console.log("Visits: %s", doc.value.visits);
if (done >= 4) {
collection.drop(function(err) {
client.close();
});
}
}
var incrementVisits = {
'$inc': {
'visits': 1
}
};
var options = { returnOriginal: false };
collection.findOneAndUpdate(findKey, incrementVisits, options, onDone);
collection.findOneAndUpdate(findKey, incrementVisits, options, onDone);
collection.findOneAndUpdate(findKey, incrementVisits, options, onDone);
collection.findOneAndUpdate(findKey, incrementVisits, options, onDone);
});
});
Note those "four" calls at the end do not resolve immediately. These simply queue up async functions and there is no guaranteed order to their execution.
But the script will return:
Visits: 1
Visits: 2
Visits: 3
Visits: 4
A much better and "modern" example would instead be:
const { MongoClient } = require("mongodb");
const uri = "mongodb://localhost:27017/";
const options = { useNewUrlParser: true };
const website = {
url: 'http://www.google.com',
visits: 0
};
const findKey = { url: 'http://www.google.com' };
(async function() {
try {
const client = await MongoClient.connect(uri,options);
const db = client.db('demo');
const collection = db.collection('websites');
await collection.insertOne(website);
var times = 4;
while (times--) {
let doc = await collection.findOneAndUpdate(
findKey,
{ $inc: { visits: 1 } },
{ returnOriginal: false },
);
console.log("Visits: %s", doc.value.visits);
}
await collection.drop();
client.close();
} catch(e) {
console.error(e);
} finally {
process.exit();
}
})()
Since we actually await each call executed in the while loop, we guarantee that these are actually executed sequentially. We also await everything, so the code is clean and ordered and we can just hang up the database connection when everything is done, without waiting on callbacks to resolve or other methods.

It seems you Mongo instance returns some kind of error, which makes the results parameter undefined. So, check for errors in the line before (which you should do anyway, but maybe with a more sophisticated error handling):
collection.find(findKey).toArray(function(err, results) {
// this is added
if( err ) {
console.log( err );
return;
}
console.log('Visits:', results[0].visits);
//cleanup
collection.drop(function() {
client.close();
});
});

Instead of
console.log('Visits:', results[0].visits);
Try printing out :
console.log('Visits:', results[0]);
so that from results[0] you can check if there exits a property 'visits'

Related

Expressjs does not execute sequencially and function return does not work

I am new to node/express js, and trying to execute the following. The control executes the lines after function call "var nextVersion =getNextContractVersion(cid)", even before the function returns a response. As a result the value for newVersion is not updated to Contract object. Also, function getNextContractVersion(cid) returns undefined, unlike the updated nextVersion.
How do i fix this behavior, please suggest. Also, is the right way of invoking function?
// Package imports
const express = require('express');
var router = express.Router();
const mongoose = require('mongoose');
//Local imports
var { Customer } = require('../models/customer');
var { Contract } = require('../models/contract');
router.put('/:cid/contracts', (req, res) => {
var cid = req.params.cid;
var nextVersion =getNextContractVersion(cid);
var contract;
if (validateCustomerId(cid)) {
req.body.contract.forEach((item) => {
contract = new Contract({
customerID: cid,
startDate: item.startDate,
endDate: item.endDate,
conditions: item.conditions,
price: item.price,
author: item.author,
version: nextVersion
});
});
contract.save((err, docs) => {
if (!err) {
Customer.findOneAndUpdate({ customerID: cid }, { $push: { contract: contract } },
{ safe: true, upsert: true, new: true }).populate({ path: 'contract' }).exec((err1, docs1) => {
if (!err1) {
res.send(docs1).status(200);
} else {
console.log('Error is adding a new contract:' + JSON.stringify(err1, undefined, 2));
}
});
} else {
console.log('Error is updating a new customer:' + JSON.stringify(err, undefined, 2));
}
});
} else {
res.status(400).send('Bad Request - Invalid input!')
}
});
function getNextContractVersion(cid) {
var nextVersion=1;
Contract.findOne({ customerID: cid }).sort({version: 'descending'}).exec((err, doc) => {
if (!err && doc != null) {
var currentVersion = parseInt(doc.version);
nextVersion = currentVersion + 1;
}
});
return nextVersion;
}
You are mixing synchronous and asynchronous code.
Contract.findOne({ customerID: cid }).sort({version: 'descending'}).exec((err, doc) => {
if (!err && doc != null) {
var currentVersion = parseInt(doc.version);
nextVersion = currentVersion + 1;
}
});
The above code effectively says "Go to the database, find one of these objects and whenever in the future that is done, run this code that's in the exec block."
One of the ways to reason about asynchronous code from a synchronous mindset is that of promises.
Here's a semi pseudo implementation:
router.put('/:cid/contracts', (req, res) => {
var cid = req.params.cid;
return getTheMostRecentContract(cid)
.then(function(oldContract){
var nextVersion = oldContract.version +1;
if(!validateCustomerId(cid)){
return res.status(400).send('Bad Request - Invalid input!');
}
var contract;
var savePromises = [];
req.body.contract.forEach((item) => {
contract = new Contract({
customerID: cid,
startDate: item.startDate,
endDate: item.endDate,
conditions: item.conditions,
price: item.price,
author: item.author,
version: nextVersion
});
savePromises.push(contract.save());
});
return Promise.all(savePromises);
})
.then(function(resultOfAllSavePromises){
//rest of code here
}).catch(function(error){
console.log('Error is updating a new customer:' + JSON.stringify(err, undefined, 2));
return res.status(400);
})
});
function getTheMostRecentContract(cid) {
return Contract.findOne({ customerID: cid }).sort({version: 'descending'});
}
As a matter of practice though, have the database control your auto-increment values. This code won't work in a high traffic environment.

nodejs - test failing but callback being called

I have a module which I export and which has a method editHeroImage which I am trying to test using mocha, chai and sinon. The modules has two objects that are passed as arguments, connection and queries. These are mySql objects, one containing the connection to the database and the other the query strings which are defined in their separate modules. The expObj which I am exporting and trying to test is a "helper" module.
I have successfully tested other methods of this module in the same way I am trying to test this method, but, however when I run into methods which use the async module for some reason, my tests no longer behave as expected. I wonder if I am missing something in this particular case, because I have tested other modules and methods which also use async and have not come across this behaviour.
When I run the tests, it logs "HELLO!" as expected but the assertion that the callbackSpy has been called, fails.
I am losing my mind here! Please help! What is going on? Could there be contamination between test suits?
Method under test:
expObj.editHeroImage = function(connection, queries, postId, postData, callback) {
async.waterfall([
function(next) {
var qString = queries.getSinglePostById();
connection.query(qString, [postId], function(err, results) {
if (err) {
return next(err);
}
if (!results.length) {
console.log('NO POST FOUND WITH ID ' + postId);
return callback();
}
next(null, results[0].hero_image);
});
},
function(heroImageId, next) {
if (!heroImageId) {
console.log('HERO IMAGE IS NEW - NEXT TICK!');
return next();
}
// Delete resized images of hero image
var queryStr = queries.deleteResizedImages();
var resizedVals = [heroImageId];
connection.query(queryStr, resizedVals, function(err) {
if (err) {
return callback(err);
}
console.log('DELETED RESIZED IMAGES OF HERO IMAGE ' + heroImageId);
var qString = queries.updateHeroImagePath();
var values = [postData.hero_image, heroImageId];
return connection.query(qString, values, function(err, results) {
if (err) {
return next(err);
}
console.log('UPDATED HERO IMAGE ' + heroImageId + ' WITH PATH ' + postData.hero_image);
next('break');
});
});
},
function addHeroImage(next) {
var qString = queries.insertImage();
var values = [postData.hero_image, postId];
connection.query(qString, values, function(err, results) {
if (err) {
return next(err);
}
next(null, results.insertId);
});
},
function addHeroImagePathToPost(heroImageId, next) {
var qString = queries.saveHeroImageId();
var values = [heroImageId, postId];
connection.query(qString, values, function(err) {
if (err) {
return next(err);
}
next();
});
}
], function(err) {
if (err && err !== 'break') {
return callback(err);
}
console.log('HELLO!');
callback(null);
});
};
Test, with set-up:
'use strict';
var chai = require('chai');
var sinonChai = require("sinon-chai");
var proxyquire = require('proxyquire');
var sinon = require('sinon');
chai.use(sinonChai);
var expect = chai.expect;
describe('HELPERS', function() {
var testedModule,
callbackSpy,
fakeConnectionObj,
fakeQueriesObj,
fakePost,
fakeSnakeCaseObj,
queryStub,
connectionStub,
manageStub,
fakeCamelCaseObj;
beforeEach(function() {
fakePost = {};
fakeConnectionObj = {};
fakeQueriesObj = {
getPostIdFromImage: function() {},
insertResizedImages: function() {},
createPost: function() {},
getPostImages: function() {},
getPostsAlternativesImages: function() {},
getSinglePostById: function() {},
getAllImages: function() {},
insertImage: function() {},
deleteMainImage: function() {},
deleteResizedImages: function() {},
updateHeroImagePath: function() {},
saveHeroImageId: function() {}
};
afterEach(function() {
queryStub.resetBehavior();
});
fakeSnakeCaseObj = {
sub_title: '123',
hero_image: '456'
};
fakeCamelCaseObj = {
subTitle: '123',
heroImage: '456'
};
callbackSpy = sinon.spy();
queryStub = sinon.stub();
manageStub = sinon.stub();
connectionStub = {query: queryStub};
testedModule = proxyquire('./../../../../lib/modules/mySql/workers/helpers', {
'./../../../factories/notification-service': {
select: function() {
return {manageSns: manageStub};
}
}
});
});
it('edits hero image', function() {
var _post = {
id: '123',
title: 'vf',
sub_title: 'vf',
slug: 'vf',
reading_time: 4,
created_at: '123',
published_at: '123',
deleted_on: false,
hero_image: 'hero_image_path'
};
var _postId = '123';
queryStub.onCall(0).callsArgWith(2, null, [{hero_image: '55'}]);
queryStub.onCall(1).callsArgWith(2, null);
queryStub.onCall(2).callsArgWith(2, null);
testedModule.editHeroImage(connectionStub, fakeQueriesObj, _postId, _post, function() {
console.log(arguments); // --> {'0': null} as expected
callbackSpy.apply(null, arguments);
});
expect(callbackSpy).has.been.calledWith(null);
});
});
Your assertion is probably executing before your async function has returned.
There are a number of ways to ensure your async functions have finished executing. The cleanest is to format your mocha test differently.
describe('...', function () {
var callbackSpy;
before(function () {
var _post = {
id: '123',
title: 'vf',
sub_title: 'vf',
slug: 'vf',
reading_time: 4,
created_at: '123',
published_at: '123',
deleted_on: false,
hero_image: 'hero_image_path'
};
var _postId = '123';
queryStub.onCall(0).callsArgWith(2, null, [{
hero_image: '55'
}]);
queryStub.onCall(1).callsArgWith(2, null);
queryStub.onCall(2).callsArgWith(2, null);
return testedModule.editHeroImage(connectionStub, fakeQueriesObj, _postId, _post, function () {
console.log(arguments); // --> {'0': null} as expected
callbackSpy.apply(null, arguments);
});
});
it('edits hero image', function () {
expect(callbackSpy).has.been.calledWith(null);
});
});
Notice that I have wrapped your assertion in a describe block so we can use before. Your actual logic for setting up stubs and executing the class has been moved to the before block and a return added, this ensures the async function is complete before moving on to your assertions.
Your other tests may have passed, but they will also be susceptible to this and it is purely a timing issue.
Indeed #Varedis was right about it being a timing issue. However using your suggestion of wrapping the assertion in a describe bloack and using the before function to set-up the test resulted in my stubs no longer working correctly. However taking your suggestion about timing into account I managed to solve the issue by using the done callback within my test suit. By keeping the set-up I made a slight change and my tests suddenly passed:
it('edits hero image', function(done) {
var _post = {
id: '123',
title: 'vf',
sub_title: 'vf',
slug: 'vf',
reading_time: 4,
created_at: '123',
published_at: '123',
deleted_on: false,
hero_image: 'hero_image_path'
};
var _postId = '123';
queryStub.onCall(0).callsArgWith(2, null, [{hero_image: '55'}]);
queryStub.onCall(1).callsArgWith(2, null);
queryStub.onCall(2).callsArgWith(2, null);
testedModule.editHeroImage(connectionStub, fakeQueriesObj, _postId, _post, function() {
callbackSpy.apply(null, arguments);
expect(callbackSpy).has.been.calledWith(null);
expect(callbackSpy).has.not.been.calledWith('FDgdjghg');
done();
});
});

I am having issues with exporting in node

I am trying to make an api endpoint for data coming from dynamoDB. I believe that I have everything connected but when I run postman to check the api (api/db) it doesn't recognize the functions from the db.js in the db.js (for routes). I have run a test on api/test and am getting the information back. Here is the code from both files:
1. This scans the database and I'm trying to export it to another file.
var AWS = require('aws-sdk');
var params = {
TableName : "iotbuttonsn",
//KeyConditionExpression: "serialNumber =:serialNumber",
//ExpressionAttributeValues: {
// ":serialNumber":"*"
//},
ScanIndexForward: false,
Limit: 3,
Select: 'ALL_ATTRIBUTES'
};
AWS.config.update({
region: "us-east-1",
endpoint: "https://dynamodb.us-east-1.amazonaws.com"
});
var docClient = new AWS.DynamoDB.DocumentClient();
var getDatabase = (function(){
return {
scanDB: function(){
docClient.scan(params, onScan);
var onScan = function(err, data){
if (err) {
console.log(err.message);
} else {
console.log('scan success');
len = data.Items.length;
for (n=0; n<len; n++) {
clickTypes[n] = data.Items[n].payload.clickType;
serialNums[n] = data.Items[n].serialNumber;
}
}
};
},
clickTypes: [],
serialNums: []
};
})();
module.exports = getDatabase;
2. This is where I'm trying to input but db.scanDB() isn't working:
var router = require('express').Router();
var db = require('../routes/db.js');
router.get('/', function(req, res){
db.scanDB();
buttons =
[
iot_buttonOne = {
serialNum: db.serialNum[0],
clickType: db.clickTypes[0]
},
iot_buttonTwo = {
serialNum: db.serialNum[1],
clickType: db.clickTypes[1]
}
]
.then(
function scanSuccess(data){
res.json(data);
},
function scanError(err){
res.send(500, err.message);
}
);
});
module.exports = router;
Change your db.scan() function to properly return an asynchronous result:
// db.js
module.exports = {
scanDB: function(cb){
docClient.scan(params, function(err, data) {
var clickTypes = [], serialNums = [];
if (err) {
console.log(err.message);
cb(err);
} else {
console.log('scan success');
len = data.Items.length;
for (n=0; n<len; n++) {
clickTypes[n] = data.Items[n].payload.clickType;
serialNums[n] = data.Items[n].serialNumber;
}
cb(null, {clickTypes, serialNums});
}
});
}
};
Then, when you use it:
var db = require('../routes/db.js');
db.scanDB(function(err, data) {
if (!err) {
// data.clickTypes
// data.serialNums
} else {
// process error
}
});
It really does not good to put the scanDB result on the DB object the way you were doing because there was no way for the caller to know when the asynchronous operation was done. So, since you have to provide some notification for the caller when the async operation is done (either via callback or promise), you may as well just pass the results there too.
Also, the .then() handler in your router.get(...) handler does not belong there. I don't know why it's there at all as there are no promises involved in the code you show. Perhaps a cut/paste error when creating the question?
Note, I removed the IIFE from your getDatabase() definition since there was no benefit to it other than a little more complicated code.

node js mongo db dependencies (doc not being found)

I have the following code:
var method = PushLoop.prototype;
var agent = require('./_header')
var request = require('request');
var User = require('../models/user_model.js');
var Message = require('../models/message_model.js');
var async = require('async')
function PushLoop() {};
method.startPushLoop = function() {
getUserList()
function getUserList() {
User.find({}, function(err, users) {
if (err) throw err;
if (users.length > 0) {
getUserMessages(users)
} else {
setTimeout(getUserList, 3000)
}
});
}
function getUserMessages(users) {
// console.log("getUserMessages")
async.eachSeries(users, function (user, callback) {
var params = {
email: user.email,
pwd: user.password,
token: user.device_token
}
messageRequest(params)
callback();
}, function (err) {
if (err) {
console.log(err)
setTimeout(getUserList, 3000)
}
});
}
function messageRequest(params) {
var url = "https://voip.ms/api/v1/rest.php?api_username="+ params.email +"&api_password="+ params.pwd +"&method=getSMS&type=1&limit=5"
request(url, function(err, response, body){
if (!err) {
var responseObject = JSON.parse(body);
var messages = responseObject.sms
if (responseObject["status"] == "success") {
async.eachSeries(messages, function(message, callback){
console.log(params.token)
saveMessage(message, params.token)
callback();
}, function(err) {
if (err) {
console.log(err)
}
// setTimeout(getUserList, 3000)
})
} else {
// setTimeout(getUserList, 3000)
}
} else {
console.log(err)
// setTimeout(getUserList, 3000)
}
});
setTimeout(getUserList, 3000)
}
function saveMessage(message, token) {
// { $and: [ { price: { $ne: 1.99 } }, { price: { $exists: true } }
// Message.find({ $and: [{ message_id: message.id}, {device_token: token}]}, function (err, doc){
Message.findOne({message_id: message.id}, function (err, doc){
if (!doc) {
console.log('emtpy today')
var m = new Message({
message_id: message.id,
did: message.did,
contact: message.contact,
message: message.message,
date: message.date,
created_at: new Date().toLocaleString(),
updated_at: new Date().toLocaleString(),
device_token: token
});
m.save(function(e) {
if (e) {
console.log(e)
} else {
agent.createMessage()
.device(token)
.alert(message.message)
.set('contact', message.contact)
.set('did', message.did)
.set('id', message.id)
.set('date', message.date)
.set('message', message.message)
.send();
}
});
}
}) //.limit(1);
}
};
module.exports = PushLoop;
Which actually works perfectly fine in my development environment - However in production (i'm using Openshift) the mongo documents get saved in an endless loop so it looks like the (if (!doc)) condition always return true therefore the document gets created each time. Not sure if this could be a mongoose issue - I also tried the "find" method instead of "findOne". My dev env has node 0.12.7 and Openshift has 0.10.x - this could be the issue, and i'm still investigating - but if anybody can spot an error I cannot see in my logic/code please let me know
thanks!
I solved this issue by using a "series" like pattern and using the shift method on the users array. The mongoose upsert findOneOrCreate is good however if there is a found document, the document is returned, if one isn't found and therefore created, it's also returned. Therefore I could not distinguish between the newly insert doc vs. a found doc, so used the same findOne function which returns null if no doc is found I just create it and send the push notification. Still abit ugly, and I know I could have used promises or the async lib, might refactor in the future. This works for now
function PushLoop() {};
var results = [];
method.go = function() {
var userArr = [];
startLoop()
function startLoop() {
User.find({},function(err, users) {
if (err) throw err;
users.forEach(function(u) {
userArr.push(u)
})
function async(arg, callback) {
var url = "https://voip.ms/api/v1/rest.php?api_username="+ arg.email +"&api_password="+ arg.password +"&method=getSMS&type=1&limit=5"
request.get(url, {timeout: 30000}, function(err, response, body){
if (!err) {
var responseObject = JSON.parse(body);
var messages = responseObject.sms
var status = responseObject.status
if (status === "success") {
messages.forEach(function(m) {
var message = new Message({
message_id: m.id,
did: m.did,
contact: m.contact,
message: m.message,
date: m.date,
created_at: new Date().toLocaleString(),
updated_at: new Date().toLocaleString(),
device_token: arg.device_token
});
var query = { $and : [{message_id: m.id}, {device_token: arg.device_token}] }
var query1 = { message_id: m.id }
Message.findOne(query).lean().exec(function (err, doc){
if (!doc || doc == null) {
message.save(function(e) {
console.log("message saved")
if (e) {
console.log("there is an error")
console.log(e)
} else {
console.log(message.device_token)
var messageStringCleaned = message.message.toString().replace(/\\/g,"");
var payload = {
"contact" : message.contact,
"did" : message.did,
"id" : message.message_id,
"date" : message.date,
"message" : messageStringCleaned
}
var note = new apns.Notification();
var myDevice = new apns.Device(message.device_token);
note.expiry = Math.floor(Date.now() / 1000) + 3600; // Expires 1 hour from now.
note.badge = 3;
note.alert = messageStringCleaned;
note.payload = payload;
apnsConnection.pushNotification(note, myDevice);
}
})
}
});
});
}
else {
console.log(err)
}
}
});
setTimeout(function() {
callback(arg + "testing 12");
}, 1000);
}
// Final task (same in all the examples)
function series(item) {
if(item) {
async( item, function(result) {
results.push(result);
return series(userArr.shift());
});
} else {
return final();
}
}
function final() {
console.log('Done');
startLoop();
}
series(userArr.shift())
});
}
}
module.exports = PushLoop;

error handle in promise nodejs + postgresql

I just start learning nodejs below is my code ...
Q1. Do I handle the error message correct way with insertUserPendingBase()??
I check the return message if equal success or not. And if so what is the then can do in this example?
Q2. I use pg when I do execute the query do I need to do anything for prevent SQL injection? I saw in document there's no need, but I'm not sure..
any suggestions can improve my code will be welcome
routes
var express = require('express');
var router = express.Router();
var co = require('co');
// .. post
var insertUserPendingBase = function(token) {
return new Promise(function (fulfill, reject){
var query = "INSERT INTO user_pending_base (user_pending_email,user_pending_password,token_timestamp,token) VALUES ('" + user_email + "','" + user_password + "', CURRENT_TIMESTAMP,'" + token + "')";
dbClient.query(query, function(err, result) {
if (err) {
reject(err);
} else {
fulfill('success');
}
});
});
// .then(function(value) {
// console.log(value);
// throw "error message";
// }).catch(function(e) {
// console.log(e);
// });
}
co(function *() {
// ...
var insertUserPendingBaseResult = yield insertUserPendingBase(generateTokenResult);
console.log('insertUserPendingBaseResult:'+insertUserPendingBaseResult);
if (insertUserPendingBaseResult == 'success') { // handle error like this ??
}
res.render('Account/Register/Index', {
partials: {
Content: 'Account/Register/Content',
}
});
}).catch(onerror);
function onerror(err) {
console.error(err.stack);
}
Update
If I change fulfill(result) instead of fulfill('success') I will get below object but there's no message about fail or success
{ command: 'INSERT',
rowCount: 1,
oid: 0,
rows: [],
fields: [],
_parsers: [],
RowCtor: null,
rowAsArray: false,
_getTypeParser: [Function] }
Update 2
I find a way use try and catch inside co(function *() like below, but I'm not sure is this the best way make a clean code ?
co(function *() {
...
try {
var insertUserPendingBaseResult = yield insertUserPendingBase(generateTokenResult);
// if success ...
} catch (err) {
// if fail
console.log(err);
}
Cannot comment on SQL injection, but fulfill('success') must be fulfill(result).
To handle success and failure of the promise you should use then and catch, no need for generators:
insertUserPendingBase.then(function(result) { /* handle result here */ })
.catch(function(ex) { /* handle exception here */ })

Resources