Parse Update Row in Node.js - javascript

I'm trying to run the following code:
exports.updateProfile = function(req, res) {
var Profile = Parse.Object.extend("Profile");
var query = new Parse.Query(Profile);
query.equalTo("username", req.body.username);
query.first({
success: function(Profile) {
Profile.save(null, {
success: function(profile) {
profile.set(req.body, { //It breaks here...
success: function(object) {
res.send({"error":"none"});
},
error: function (object, error) {
res.send({"error":"Error: " + error.code + " " + error.message});
}
});
},
error: function (object, error) {
res.send({"error":"Error: " + error.code + " " + error.message});
}
});
},
error: function (object, error) {
res.send({"error":"Error: " + error.code + " " + error.message});
}
});
}
However, neither the success nor error methods are called at the "It breaks here" line. Any ideas or better ways to update Parse rows using Node.js? Thanks.

exports.updateProfile = function(req, res) {
var Profile = Parse.Object.extend("Profile");
var query = new Parse.Query(Profile);
query.equalTo("username", req.body.username);
query.first().then(function(Profile){
Profile.set("columnName", value);//value might be you are getting from req.body
Profile.save().then(function(saved){
res.send({"error":"none"});
}, function(error){
res.send(error);
});
}, function(error){
res.send(error);
});
}
This might be the thing you are looking for. Try this approach hope it will help. You were saving an object that is not yet modified, That could be the reason why it is not coming to the call back method. Refactored the code to remove the invalid save call.

Related

libphonejs - how to use it?

I've got the following attempt to send an SMS
var number = '**********'
sendText: function(phone, callback) {
// maybe needs a .then() ?
var formattedPhone = Phone.format(Phone.parse(phone, 'US'), 'International_plaintext')
var messageBody = 'test'
client.sms.messages.create({
to: formattedPhone,
from: number,
body: messageBody
})
}, function(error, message) {
if (error) {
console.log("SMS ERROR sending to: " + formattedPhone)
callback(error)
} else {
console.log("SMS sent to: " + formattedPhone)
callback(null, message)
}
}
It doesn't print an error or a success string to console - is it the Phone.format(Phone.parse()) call that's causing it by blocking the thread or something?
You have syntax error. The callback function for error message is outside the braces.
https://github.com/TwilioDevEd/api-snippets/blob/master/rest/messages/send-message/example-1.2.x.js
sendText: function(phone, callback) {
// maybe needs a .then() ?
var formattedPhone = Phone.format(Phone.parse(phone, 'US'), 'International_plaintext')
var messageBody = 'test';
client.sms.messages.create({
to: formattedPhone,
from: number,
body: messageBody
/*})*/ // remove this should be deleted
}, function(error, message) {
if (error) {
console.log("SMS ERROR sending to: " + formattedPhone)
callback(error)
} else {
console.log("SMS sent to: " + formattedPhone)
callback(null, message)
}
});
}

how to access an exported json object in node.js

Dopey question. I have an object from a library and I want to access it but I just don't get it. Here is the exported object:
exports.listAccounts = function(successCallback,errorCallback)
{
var actionDescriptor = {
method : "GET",
module : "accounts",
action : "accountlist",
useJSON: true,
};
this._run(actionDescriptor,{},successCallback,errorCallback);
};
Now I want to access the account list in code at etListAccounts:
//user sends confirmation code and we get acesss token
app.get('/users/sendcode', function (req, res) {
console.log('verification CODE is '+req.query.vCode);
//end get verification code
et.getAccessToken(req.query.vCode,
function() {
console.log('thread entered getAccessToken function')
et.listAccounts(
function(){console.log('account list success')},
function(error) {
console.log("Error encountered while attempting " +
"to retrieve account list: " +
error);
});
// console.log(accountlist[0]);
},
function(error) {
console.log("Error encountered while attempting " +
"to exchange request token for access token: " +
error);
}
);
})
I've tried this:
et.listAccounts(
function(accountList){console.log('account list success')},
function(error) {
console.log("Error encountered while attempting " +
"to retrieve account list: " +
error);
});
And I've tried this:
et.listAccounts(
function(){accountList},
function(error) {
console.log("Error encountered while attempting " +
"to retrieve account list: " +
error);
});
And I've tried this:
accountList - et.listAccounts(
function(){console.log('account list success')},
function(error) {
console.log("Error encountered while attempting " +
"to retrieve account list: " +
error);
});
This is a nice simple question and I feel foolish for asking it but lots of people can answer it and lots of beginners will find it useful.
From the snippet you shared with us, it appears that you are not importing the module. Please read the documentation here:
https://nodejs.org/docs/latest/api/modules.html#modules_accessing_the_main_module
var imported = require('nameOfModule');

Adding Users to Parse Role in Cloud Code

I want to add users to my Parse.Role but it's not working. I looked at a number of examples and they all seem pretty straight-forward however I'm unable to get it right. Here is my code:
Parse.Cloud.define("activateVendor", function(request, response){
var query = new Parse.Query(Parse.Role);
query.equalTo("name", "vendor");
query.first ({
success: function(role) {
role.getUsers().add(request.params);//request.params is the parse object, should I be using request.params.id?
role.save();
},
error: function(error) {
throw "Got an error " + error.code + " : " + error.message;
}
})
});
It depends on who you wish added to the role. The user who made the cloud request is available via the request object...
role.getUsers().add(request.user);
Otherwise, you can get a user via a query as #RobertRowntree suggests. (though, I'd suggest doing it with promises).
does what you want with 2 queries (Role, User) ...
var qu = new Parse.Query(Parse.User);
var qr = new Parse.Query(Parse.Role);
Parse.Cloud.useMasterKey();
qr.get(roleId, {
success: function(role) {
_role = role;
qu.get(userId, {
success: function(user) {
_role.getACL().setRoleReadAccess(_role, true);
_role.getUsers().add(user);
_role.save();
response.success(_role.toJSON());
},
error: function(object, error) {
}
});
},
error: function(object, error) {
}
});

Azure mobile service invokeApi not working from cordova project

I'm using Azure Mobile Services(AzMS) in VisualStudio JS-Apache Cordova project where I call a AzMS's custom API to insert user data in storage. This very same code I have previously used in a VS web app javascript and there it is working fine.
However here in the cordova project, I get an "unexpected connection failure" error when calling invokeApi. When I try from VS web app, it works fine, which means the custom API service code is good.
Here is my js client code:
azmsClient.login(oAuthProvider).done(function (results) {
console.log("You are now logged in as: " + results.userId);
var theUserAuthId = results.userId;
azmsClient.invokeApi('Users/insert', {
method: 'POST',
body: { userAuthId: theUserAuthId }
}).done(function (response) {
//.... success code
},
function (error) {
console.log("Error: " + err.request.responseText);
//.... error handling
});
},
function (err) {
console.log("Error: " + err.request.responseText);
//.... error handling
});
In the console log, the first log ("You are now logged in as: "..) gets logged, after that the error - unexpected connection failure.
And my azure custom Api code -
var logger = require('../api/logUtils.js').logger;
exports.register = function(api){
api.post('insert', insertUser);
};
/******************************************************************
* #param request
* #param response
*******************************************************************/
function insertUser(request, response){
var user = request.user;
var iM = "api.User.insertUser-";
logger.info( iM + ' called: - ' , request, response, user);
// Data validation
if ( user.level === 'anonymous' ) {
logger.error( iM + 'Anonymous User' );
response.send(500, { error: "Anonymous user." });
}
user.getIdentities({
success: function (identities) {
var req = require('request');
var userId = user.userId.split(':')[1];
var theProvdr = user.userId.split(':')[0];
var reqParams;
logger.info(iM + ': calling getOAuthUserDetails for Identities: - ' , identities);
try {
reqParams = getOAuthUserDetails(userId, identities);
}
catch(err){
logger.error(iM + ': getOAuthUserDetails - ' , err);
response.send(500, { error: err.message });
return;
}
req.get(reqParams, function (err, resp, body) {
if (err) {
logger.error(iM + ': Error calling provider: ', err);
response.send(500, { error: 'Error calling Authentication provider' });
return;
}
if (resp.statusCode !== 200) {
logger.error(iM + ': Provider call did not return success: ', resp.statusCode);
response.send(500, { error: 'Provider call did not return success: ' + resp.statusCode });
return;
}
try {
logger.info(iM + ': success: got User Details body ', body);
var theAppUser = oAuthUser_To_appUser(theProvdr, JSON.parse(body));
addUser(theAppUser, user, {
success: function(userAlreadyExist, userEnt){
logger.info( iM + ': addUser: success', userEnt);
response.send(200, getAppUserEnt(userEnt));
},
error: function(err){
logger.error( iM + ': Error in addUser: ', err);
response.send(500, { error: err.message });
}
});
} catch (err) {
logger.info(iM + ': Error parsing response: ', err);
response.send(500, { error: err.message });
}
});
},
error: function(err){
logger.info(iM + ': error on calling getIdentities: - ' , err);
response.send(500, { error: err.message });
}
});
In the azure service logs, I see no entry logged from the custom api's user.insert function when running from the cordova project, which means the api is got getting called. Like said before, when calling from VS web project, the log records look all good.
(this is somewhat similar to the issue asked here, but not exactly the same.)
I am unable to figure out why its happening so; any idea?
Are you running on a device, emulator, or Ripple. If its Ripple, you have to change the Cross Domain Proxy to 'disabled'. I had similar issues and this seemed to help.

XMLHttpRequestError issue when signing up user using parse

I'm trying to use Parse.com to sign users up to my application I'm developing. However I seem to get an error when firing my function.
Parse.initialize("APP ID", "JS KEY");
function signUp() {
var user = new Parse.User();
// Get user inputs from form.
var username = document.login.username.value;
var password = document.login.password.value;
user.set("username", username);
user.set("password", password);
user.signUp(null, {
success: function (user) {
// Hooray! Let them use the app now.
alert("Success");
},
error: function (user, error) {
// Show the error message somewhere and let the user try again.
alert("Error: " + error.code + " " + error.message);
}
});
};
The error:
Error: 100 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}
Any help here would be great, i'm unsure what's causing the error. Seems to work correctly when i'm not passing form data through it. Thanks.
I think you instead should use:
user.setUsername(username);
user.setPassword(password);
Also, these can be combined:
Parse.User.signUp(username, password, { ACL: new Parse.ACL() }, {
success: function (user) {
// Hooray! Let them use the app now.
alert("Success");
},
error: function (user, error) {
// Show the error message somewhere and let the user try again.
alert("Error: " + error.code + " " + error.message);
}
});

Categories