I am trying to poll respondents that have changed answers or get new respondents but this code appears to pull in all of the data regardless. Have I got the wrong data key? The polling guide suggests adding start_modified_date but that doesn't work. Thanks in advance
var SurveyMonkeyAPI = require('surveymonkey').SurveyMonkeyAPI;
try {
var api = new SurveyMonkeyAPI(config.surveymonkey.key, config.surveymonkey.access_token, config.surveymonkey.params);
} catch (error) {
console.log(error.message);
}
var data = {
survey_id: surveyId,
fields: ["date_created", "date_modified", "status"],
start_modified_date: lastLoadedDate.toISOString().replace(/T/, ' ').replace(/\..+/, '')
};
console.log("FETCHING ", surveyId, data);
this.api.getRespondentList(data, this.bind(function (error, data) {
if (error)
console.log(error.message);
else
console.log(JSON.stringify(data)); // Do something with your data!
});
Here is the fork that has it fixed https://github.com/GeorgePhillips/node-surveymonkey
Related
I am writing cloud functions on Cloud Firestore triggers. What I want is when a document is added under some uuid it has to deleted after 2 minutes and assign the same data to another document. I wrote some code regarding that like below
exports.createdOpenOrder = functions.firestore.document('Some/{psId}/Open/{OrderId}').onCreate((snap, context) => {
// Get an object representing the document
console.log("Deleting function execution started:");
const newValue = snap.data();
var OrderId = context.params.OrderId;
var psId = context.params.psId;
setTimeout(delete_cur, 120000);
function delete_cur() {
var data = db.collection('Some').doc(psId).collection('Open').doc(OrderId).delete().then(function() {
console.log("Document successfully deleted!");
// calling another function to reassign
reassign(OrderId);
return;
}).catch(function(error) {
console.error("Error removing document: ", error);
return;
});
}
});
Now my problem is the setTimeout function is not calling exactly after 2 minutes and data is not deleting. Is anything wrong with my code? Please let me know how to write code work perfectly on setTimeout.
To find the problem, put log before, and a catch around, the contents of your setTimeout handler.
Currently you are only trapping exceptions after the delete async function returns. All other exceptions in the chain, before calling delete, are not caught.
function delete_cur() {
console.log('handler called')
try {
var data = db.collection('Some').doc(psId).collection('Open').doc(OrderId).delete().then(function() {
console.log("Document successfully deleted!");
// calling another function to reassign
reassign(OrderId);
return;
}).catch(function(error) {
console.error("Error removing document: ", error);
return;
});
} catch (e) {
console.error('could not invoke delete', e)
}
}
I have been coding my small project but I'm facing a problem.
here is my code:
app.get('/thu', (req, res) => {
thu(function(err, output){
if(err){
res.json({"err": ""+err, "output": output});
return;
}
res.send("ket qua: ", output);
});
});
var thu = function(callback){
web3.eth.getTransactionCount(senderAddress).then((txnCount) => {
console.log("goi thu");
var method = contract.methods.thu();
var encodedABI = method.encodeABI();
var thuTx = {
from: senderAddress,
to: contractAddress,
nonce: web3.utils.toHex(txnCount),
gasLimit: web3.utils.toHex(GAS_LIMIT),
gasPrice: web3.utils.toHex(GAS_PRICE),
data: encodedABI,
};
sendTxn(thuTx, callback);
}).catch((err) => {
console.log("web3 err", err);
callback(err, null);
});
};
function sendTxn(rawTx, callback) {
var privateKeyBuffer = new Buffer(privateKey, 'hex');
var transaction = new tx(rawTx);
transaction.sign(privateKeyBuffer);
var serializedTx = transaction.serialize().toString('hex');
web3.eth.sendSignedTransaction(
'0x' + serializedTx, function(err, txnHash) {
if(err) {
console.log("txn err", err);
callback(err, null);
} else {
console.log("txn result", txnHash);
}
}).catch((err) => {
callback(err, null);
});
}
I'm sure that my smart contract runs ok. when I hit submit the code send a transaction to Rinkeby and it is ok. but I cannot receive any responses.
Please help my solve my problems. thank you.
sendSignedTransaction returns a Promise combined event emitter.
Ethereum as a blockchain has different levels of finality and
therefore needs to return multiple “stages” of an action. To cope with
requirement we return a “promiEvent” for functions like
web3.eth.sendTransaction or contract methods. This “promiEvent” is a
promise combined with an event emitter to allow acting on different
stages of action on the blockchain, like a transaction.
You can place a console.log on every event, to see what is happening, or if you're getting an error.
web3.eth.sendSignedTransaction('0x' + serializedTx)
.once('transactionHash', hash => console.log(`Hash: ${hash}`)
.once('receipt', receipt => console.log(`Receipt: ${receipt}`)
.on('confirmation', (confNumber, receipt) => console.log(confNumber))
.on('error', error => console.error(error))
.then(receipt => {
// will be fired once the receipt its mined
});
Problems solved. the problem is I forgot the put the callback(...) in else {...}.
I am work with isntagram api in node js. i have one array and in the array store above 20k up instagram id. and then i am do foreach on that array and one by one take instagram id and go for the take bio but that time i am getting error like this RequestsLimitError: You just made too many request to instagram API. i am try every 5 call after set time out also but still i am getting same error so how can resolved this error any one know how can fix it then please let me know.
Here this is my code =>
var InstaId = ["12345687",20k more id store here in the array]
var changesessionFlage = 0;
async.each(InstaId, function (id, callback) {
async.parallel([
function (cb) {
if (id) {
setTimeout(function () {
Client.Account.getById(sess, id).then(function (bio) {
console.log("changesessionFlage" + changesessionFlage);
changesessionFlage++
//console.log("bio : ", bio._params); // here i am getting bio one by one user
if (changesessionFlage == 6) {
changesessionFlage = 0;
}
cb(null, bio._params);
})
.catch(function (err) {
console.log("get boi: ", err)
cb(null, bio._params);
})
}, (changesessionFlage == 5) ? 10000 : 0)
}
}
], function (err, results) {
if (err) {
console.log(err);
return;
}
Result = results
callback();
});
}, function (err) {
if (err) {
console.log(err);
return;
}
else {
console.log("Result=>", Result)
if (Result) {
console.log("Result[0]=>", Result[0])
var ws = XLSX.utils.json_to_sheet(Result[0]);
var wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "People");
var wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });
res.end(wbout, 'binary');
}
}
});
any one know how can fix this issue then please help me.
Your setTimeout is use incorrectly, all API calls are made at once after 10000 delay.
Since this is a one time job, just split the 20K usernames to 4K batches and execute them every hour. This way you will be under the 5k/hr API limit
I'm totally new to nodejs. I would like to ask your expertise regarding for error handling using connection.beginTransaction(); with this sample code.
connection.beginTransaction(function(){
async.parallel([
function(callback){
connection.query('INSERT INTO SUBJECT.PROJECT (Name, Score) VALUES (?,?)',
['Drake', '85']
, function(error){
//if(error)
// connection.rollback();
callback(error);
});
},
function(callback){
connection.query(someUpdateQuery, someValues,
function(error){
//if(error)
// connection.rollback();
callback(error);
});
}
], function(error){
var msg;
if(error) {
connection.rollback();
msg = 'Error! ' + error;
}
else {
connection.commit();
msg = 'Success';
}
res.json(msg);
});
});
With this sample code, Is this doable?
Every connection.query has connection.rollback() in if(error), can I remove connection.rollback() in each
connection.query and rely in the last function instead to handle the
connection.rollback()? - will it rollback all (lets say) 10 inserting query functions then the 5th 1 got the error.
Sorry, I don't know much,. thanks for reading
You are correct - you can remove the rollback statements of the individual queries and rely on the one in the async.parallel callback. Your code would look something like this:
connection.beginTransaction(function () {
async.parallel([
function (callback) {
connection.query('INSERT INTO SUBJECT.PROJECT (Name, Score) VALUES (?,?)',
['Drake', '85']
, callback);
},
function (callback) {
connection.query(someUpdateQuery, someValues, callback);
}
], function (error) {
var msg;
if (error) {
connection.rollback();
msg = 'Error! ' + error;
}
else {
connection.commit();
msg = 'Success';
}
res.json(msg);
});
});
This works because non of the commands will be committed to the database until you call connection.commit() in the final callback. One thing you might want to look at is whether the commit and rollback methods are asynchronous, i.e. they expect you to pass a callback to them. If so your code as it is will run res.json before the transaction has been committed or rolled back.
I'm trying to do something relatively simple and am running into a "server ...-a.mongolab.com:36648 sockets closed" error all of a sudden every time I try to do an "insert".
Reads seem to work without error, but inserts seem to get an error every time and I'm not sure if it's my code (which recently underwent minor changes), or a reliability problem with the free server I'm using at MongoLab (which recently showed itself to be down for a few minutes).
Oddly enough, the record itself seems to save okay, I just get the error back!
Can anyone see an issue with my code, or could this be something else?
var mongoClient = require('mongodb').MongoClient;
var http = require('http');
var connectionString = "...";
var pictureWallsCollectionName = 'PictureWalls';
//this is what barfs. see *** details
exports.saveWall = function (req, res) {
//reformat
var toSave = {
_id: req.body.wallId,
pictures: req.body.pictures
};
var status;
mongoClient.connect(connectionString, function (err, db) {
if (err) { return console.error(err); }
var collection = db.collection(pictureWallsCollectionName);
//*** no err yet... ***
collection.insert(
toSave,
function (error, response) {
//*********************
//*** err here! ******
//*********************
db.close();
if (error) {
console.error(error);
//bad
status = 500;
}
else {
console.log('Inserted into the ' + collection_name + ' collection');
//good
status = 200;
}
});
response.status(status).end(http.STATUS_CODES[status]);
});
}
//this seems to work pretty reliably. including it just in case it's relevant
exports.findByWallId = function (req, res) {
var id = req.params.id;
console.log('Retrieving wall: ' + id);
mongoClient.connect(connectionString, function (err, db) {
if (err) { return console.dir(err); }
var collection = db.collection(pictureWallsCollectionName);
collection.findOne(
{ _id: id },
function (err, item) {
db.close();
if (err) {
console.error(err);
//something bad happened
var status = 500;
res.status(status).end(http.STATUS_CODES[status]);
}
else {
console.log('Found wall with ID ' + id);
//reformat and send back in the response
res.send({
wallId: item._id,
pictures: item.pictures
});
}
}
);
});
};
EDIT: Part of my original issue was duplicate parameter names. See the linked question for detail.
ORIGINAL RESPONSE:
The issue ended up being that I was calling:
res.status(status).end(http.STATUS_CODES[status]);
...before the async insert was finished, so it barfed.
However, I'm not exactly sure how to issue the response in this case. See my new question here:
How Do I Properly Issue Response To Post When Waiting For Async Method To Complete?