No response from Javascript SDK find call - javascript

I'm working with the cloud code javascript SDK. I'm trying to run a query, but it seems that the "find" method never receives a response. Here's what I've got so far:
var query = new Parse.Query("Report");
var sixteen_h = new Date();
sixteen_h.setHours(sixteen_h.getHours() - 16);
query.greaterThan("createdAt", sixteen_h);
query.find({
success: function(results) {
console.log("Got pain results!");
},
error: function(error) {
console.log("Error: " + error.code + " " + error.message);
}
});
Neither of these console logs are ever executed! Any ideas here? I've tried it both with and without the "query.greaterThan()" part and get no response both times. I've tried putting various log statements throughout it but can't see where it goes wrong.

I was using this in a beforeSave function. Apparently you can't do that. Once I moved this to an afterSave function then it worked fine!

Related

How can I not authenticate everytime in StackExchange API calls using JS client?

I am using this code from the StackExchange App Documentation to get the user information from StackOverflow.
// For simplicity, we're using jQuery for some things
// However, the library has no jQuery dependency
$(function(){
// Initialize library
SE.init({
// Parameters obtained by registering an app, these are specific to the SE
// documentation site
clientId: 1,
key: 'U4DMV*8nvpm3EOpvf69Rxw((',
// Used for cross domain communication, it will be validated
channelUrl: 'https://api.stackexchange.com/docs/proxy',
// Called when all initialization is finished
complete: function(data) {
$('#login-button')
.removeAttr('disabled')
.text('Run Example With Version '+data.version);
}
});
// Attach click handler to login button
$('#login-button').click(function() {
// Make the authentication call, note that being in an onclick handler
// is important; most browsers will hide windows opened without a
// 'click blessing'
SE.authenticate({
success: function(data) {
alert(
'User Authorized with account id = ' +
data.networkUsers[0].account_id + ', got access token = ' +
data.accessToken
);
},
error: function(data) {
alert('An error occurred:\n' + data.errorName + '\n' + data.errorMessage);
},
networkUsers: true
});
});
});
This code works fine but I noticed that everytime it fires and gives the response access_token changes. How I can I just get user information using the access token. Plus this is returning user's data with all the sites he is part of. How can I limit it to just StackOverflow. I am unable to find proper documentation for this.
Can anyone please point me to the JS methods for making API calls from StackExchange API?

NeDB not loading or storing to file

I cannot get the simplest example of NeDB to run properly. My code only works in-memory, persistence to file keeps failing without any error messages.
The error callbacks for the loaddatabase and insert events always pass a null reference as error, so no information there. Oddly it seems no one else has this issue, so I guess I'm missing something here. All help is much appreciated.
Here is the code:
var Datastore = require('nedb'), db = new Datastore({ filename: 'test.db' });
db.loadDatabase(function (err) {
alert(err); // err is null, with the autoload flag no error is thrown either
});
var doc = { hello: 'world'};
db.insert(doc, function (err, newDoc) {
alert(err); // err is null here as well. Doc will be in the memory storage but no persisted to file
});
Although this question is pretty old, I'd like to share my experience for anyone facing a similar issue.
NeDB API does not allow JSON input. You have to put in a javascript object. When you use JSON input, no error is returned and nothing will be persisted.
'null' is returned as error in callback to signal that no problem occurred. When saving the first JSON document it is indexed with 'undefined' key, because NeDB calls 'key = obj[fieldname[0]]' which returns 'undefined', when the obj is just a (JSON) string. No error is returned unfortunately. Inserting a second document will cause a unique constraint violation error in the callback as the key 'undefined' has already been taken. Anyhow, nothing will be persisted.
Try
var Datastore = require('nedb'), db = new Datastore({ filename: 'test.db' });
db.loadDatabase(function (error) {
if (error) {
console.log('FATAL: local database could not be loaded. Caused by: ' + error);
throw error;
}
console.log('INFO: local database loaded successfully.');
});
// creating the object with new, just to make it clear.
// var doc = {hello: 'world'}; should work too.
function myDoc(greeting)
{
this.hello=greeting;
}
var doc = new myDoc('world');
db.insert(doc, function (error, newDoc) {
if (error) {
console.log('ERROR: saving document: ' + JSON.stringify(doc) + '. Caused by: ' + error);
throw error;
}
console.log('INFO: successfully saved document: ' + JSON.stringify(newDoc));
});
Maybe it helps someone. :)
This question is quite old but since I had very similar problem I thought that I'll write my resolution for anyone facing similar issues.
In my case I was writing Electron app using electron-webpack as an application builder. It turns out that NeDB loaded by Webpack was running in browser mode without access to file system.
To get it working I had to change import statement from:
import DataStore from 'nedb';
to this:
const DataStore = require('nedb');
Also I had to add NeDB to Webpack configuration as external module (in package.json):
"electronWebpack": {
"externals": {
"nedb": "commonjs nedb"
}
}
I have found this resolution on NeDB github page: https://github.com/louischatriot/nedb/issues/329
All I had to do to fix this was delete the .db file and let the program make one for me by running it one more time.
The other thing I did that could have fixed it was making sure my package.json had all the required information. this can be easily done with a quick "npm init" in the terminal.

Parse custom webhook: can I query my tables?

In a Parse custom webhook, which is of the form:
app.post('/receiveSMS', function(req, res) {
Where receiveSMS is hooked up to the Twilio api and this method is properly called (I have logs to prove it), but I'm trying to query on my tables within this method and it doesn't seem to be working.
Is this allowed, or is there anything special I need to do to make this work?
var contactObj = Parse.Object.extend("Contact");
var contactQuery = new Parse.Query(contactObj);
console.log(req.body.From);
contactQuery.each(function(contact) {
and the body of the each call never gets called.
Is this allowed, and if so, what am I doing wrong here?
Update -- The entirety of the webhook code block is:
app.post('/receiveSMS', function(req, res) {
console.log('receive SMS');
console.log(req.body.Body);
res.send('Success');
if(req.body.Body.toLowerCase() == "in" || req.body.Body.toLowerCase() == "out") {
twilio.sendSMS({
From: "(xxx) xxx-xxxx",
To: req.body.From,
Body: "It's been noted, and notifications have been sent. Check us out!"
}, {
success: function(httpResponse) {
console.log(httpResponse);
response.success("SMS Sent!");
},
error: function(httpResponse) {
console.error(httpResponse);
response.error("Uh OH, something went wrong");
}
});
if(req.body.Body.toLowerCase() == "in") {
console.log("in was received");
// eventQuery
var contactObj = Parse.Object.extend("Contact");
var contactQuery = new Parse.Query(contactObj);
console.log(req.body.From);
// contactQuery.equalTo("phone", req.body.From);
contactQuery.first({
success: function(contact) {
console.log("found contact");
console.log(contact);
}, error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
}
});
This code is called and the logs "console.log('receive SMS')" and the like are all called, except for what is inside the query's first call.
Queries on tables is fine, but you can't use the each() function, as that is restricted to only work in background jobs.
You'll have to use find() or first() or get() depending on your needs.
UPDATE
OK, after seeing your full code I have some ideas as to why it isn't working. First off you're sending res.send("Success"); before you're finished, I'm not positive but I think this causes it to stop running the rest of your code (haven't checked, could be wrong).
Also you're doing multiple async operations without chaining them so the contactQuery.first() will run before the twilio.sendSMS() is finished.
Inside twilio.sendSMS() you're calling response.success() / response.error(). These are for cloud methods, not web hooks, so I expect these would be throwing errors server-side (check the logs on the Dashboard).
Inside contactQuery.first() you are using alert() which isn't supported in cloud code.
I'm not sure if those mistakes will be caught early and throw errors or if they'll raise run-time exceptions, but they should be fixed, your code re-deployed and try again. Then report any errors in the server logs.
Yes, it's allowed, I'm using the same web hooks.
My guess is that you probably have defined security restriction on your Contact class that prevent the query to fetch anything. What's the security setting on this class ?
You can either try to relax the constrains, or login as a dummy user, and execute the query (approach that I chose).
cheers
-A

Save success not working with parse.com object

I have been messing around trying to save data from a web form and cannot get the standard validation to return. Thinking this is some sort of async problem that I am just not getting. Saving objects with the parse.com api is built off of backbone.js, so it is pretty similar to that. For some reason I can save my data to my database no problems, but when I try to introduce some sort of validation it gets messed up. Looking for some info on how to properly get a success validation back from the server. Right now it hits error every time, and seems to kill the server from saving data.
Below is the code that executes on submit. I have shown the three ways I have tried saving data.
$("#f1").submit(function(event) {
var NewRes = Parse.Object.extend("Customer");
var newRes = new NewRes();
newRes.set("FirstName", "Ricky");
newRes.set("LastName", "Bobby");
//works every time, but I have no return validating it
newRes.save();
//saving with callback options, doesn't save anything to the database and hits error message
newRes.save(null, {
wait: true,
success: function(newRes, response) {
alert("success" + response.message);
},
error: function(newRes, response) {
alert("errorcode: " + response.code + " Message: " + response.message);
}
});
//saving with promises, doesn't save anything and hits error message
newRes.save().then(function(response) {
alert("success");
}, function(error) {
alert("error");
});
});
Here are the results of the error message given below:
errorcode: 100 Message: XMLHttpRequest failed: {"statusText":"","status":0,"response":"","responseType":"","responseXML":null,"responseText":"","upload":{"ontimeout":null,"onprogress":null,"onloadstart":null,"onloadend":null,"onload":null,"onerror":null,"onabort":null},"withCredentials":false,"readyState":4,"timeout":0,"ontimeout":null,"onprogress":null,"onloadstart":null,"onloadend":null,"onload":null,"onerror":null,"onabort":null}
The reason none of this was working is because the form.submit() function was finishing before any of the parse.com asynchronous functions were complete. In order to prevent this I used the preventdefault method to stop the form from submitting. Then I used location.reload() to refresh the page after my parse.com requests have either finished successful or failed.
$("#f1").submit(function(event) {
event.preventDefault();
var NewRes = Parse.Object.extend("Customer");
var newRes = new NewRes();
newRes.set("FirstName", "Ricky");
newRes.set("LastName", "Bobby");
//saving with promises
newRes.save().then(function(response) {
alert("success");
location.reload(); //refreshes the form
}).catch(function(error) {
alert("error");
location.reload();
});
});

How to get response from node-xmpp request?

I learned to make request with the XMPPserver by using node-xmpp library. Now i can make the request as mentioned in XMPP extensions documentations. But now i want to get the callback response for the each request (especially the XML response).
Here i have used the following code the make a request subscription (friend request) to a another user
var net = require("net");
var xmpp = require('node-xmpp');
var cl = new xmpp.Client({ jid: "one#localhost", password: "comet123$" })
cl.addListener('online', function(data) {
console.log('Connected as ' + data.jid.user + '#' + data.jid.domain + '/' + data.jid.resource)
//making subscription
var stanza = new xmpp.Element('presence',{
to: "hai#localhost",
from: "one#localhost",
type: "subscribe",
}).up
// making request
cl.send(stanza);
// nodejs has nothing left to do and will exit
cl.end()
})
I want to know, how to get the response result.
I tried with the callback functionality with as llike this,
cl.send(stanza, function(result){
console.log(result);
});
and also like this
var result = cl.send(stanza);
This returns only true,
So can anyone please tell me how do I get the callback result for the requests that we make by using the node-xmpp libarary
There is no callback or return for XMPP messages. You will have to have to set up an event listener to pick up messages coming back from the server. Add:
cl.on('stanza', function(stanza){
// Do something with the stanza
// If you want to end after the first message you get back, move this here
cl.end();
});
you can get raw data from connection
cl.connection.on("data", function (data) {
console.log('data', data.toString('utf8'));
});

Categories

Resources