jsforce ignoring callback functions? - jsforce

I tool the code right out of the docs, but it's like it completely ignores the existence is the call back functions:
var jsforce = require('jsforce');
var conn = new jsforce.Connection({
// you can change loginUrl to connect to sandbox or prerelease env.
loginUrl : 'https://ivytechfoundation--ucidev.my.salesforce.com'
});
conn.login('xxxxxx#ivytech.edu.uci.ucidev', 'xxxxxxxxTOjhPejiRZ1KWox4AmYOPzqu', function(err, userInfo) {
console.error('1');
// if (err) { return console.error(err); }
console.error(err);
console.error(userInfo);
// Now you can get the access token and instance URL information.
// Save them to establish connection next time.
console.log(conn.accessToken);
console.log(conn.instanceUrl);
// logged in user property
console.log("User ID: " + userInfo.id);
console.log("Org ID: " + userInfo.organizationId);
// ...
});
Any ideas? It never hits '1'

There seems to be a bug. I couldn't make it work either, but this works:
conn
.login(sfUserName, sfPassword + sfToken)
.then((userInfo) => { // your code here

Related

Google Action Webhook Inline Editor Returns Before the API call

This is my first Google Action project. I have a simple slot after the invocation. User enters the value on prompt and slot invokes the webhook and make a call to API using the user input. All works fine. However the webhook returns to users even before the API call finish processing and returns the value (line 1 conv.add). I do see in the logs that everything from API is logged fine after the webhook returns to user. Below is the code I am using. I am using inline editor. What am I missing? Thanks for help in advance.
const { conversation } = require('#assistant/conversation');
const functions = require('firebase-functions');
var https = require('https');
const fetch = require('node-fetch');
const app = conversation({debug: true});
app.handle('SearchData', conv => {
const body = JSON.stringify({
val: "this is my body"
});
// prepare the header
var postheaders = {
'Content-Type' : 'application/json',
'Auth' : 'MyAuthCreds'
};
fetch('https://host.domain.com/data', {
method: 'post',
body: body,
headers: postheaders,
})
.then(res => res.json())
.then(d => {
console.log(d);
var profile = d;//JSON.parse(d);
console.log(d.entries);
console.log("Length: "+ d.entries.length);
if(d.entries.length > 0)
{
console.log("Data found");
conv.add("Data found"); //line 1
}
else
{
console.log("no data found");
conv.add("no data found"); //line 1
}
})
.catch(function (err) {
// POST failed...
console.log(err);
});
});
exports.ActionsOnGoogleFulfillment = functions.https.onRequest(app);
Your issue is that your handler is making API calls which are asynchronous, but the Assistant Conversation library doesn't know that you're doing so. So as soon as the handler finishes, it tries to send back a response, but your asynchronous responses (the stuff in the then() blocks) haven't executed yet.
To address this, you need to return a Promise object so the library knows to wait till the Promise is fulfilled before it returns.
Fortunately, in your case, this should be pretty straightforward. fetch and all the .then() blocks return a Promise. So all you need to do is add a return statement in front of the call to fetch. So something like this:
return fetch('https://host.domain.com/data', {

Fromname in mail using sendgrid mail api

I'm trying to send emails using sendgrid mail API.
Everything works fine. However, I want my emails to have a specific name.
Not the prefix of the sender's address, which is coming up by default.
I changed the From value to "MY_email_name <sender#example.com>". But it didn't work.
I have set the From_Name field to "MY_email_name". That too didn't work.
However, it's working when I not read the html content from an external file and instead give some inline. In that case it is sending me the email_name.
Any idea about how I can do this with reading the content.
Thanks.
var sendgrid = require('sendgrid')('MY_APP_SECRET');
var fs = require('fs');
var content;
// First I want to read the file
fs.readFile(__dirname+'/email.html', function read(err, data) {
if (err) {
throw err;
}
content = data;
// Invoke the next step here however you like
//console.log(content); // Put all of the code here (not the best solution)
processFile(); // Or put the next step in a function and invoke it
});
function processFile() {
console.log(content);
}
module.exports = function sendMail(mailObject){
return new Promise(function (resolve, reject){
// create a new email instance
var email = new sendgrid.Email();
email.addTo('some1#example.com');
email.setFrom('sender#example.com');
email.setSubject('My-Email-body');
email.setFromName("Email-Name");
email.setHtml(content);
email.addHeader('X-Sent-Using', 'SendGrid-API');
email.addHeader('X-Transport', 'web');
email.setASMGroupID(835);
//send mail
sendgrid.send(email, function(err, json) {
//if something went wrong
if (err) { reject({
error:err,
res : json,
}); }
//else
resolve({
statusText: 'OK',
res : json
});
});
})
}

TypeError: Cannot read property 'cookie' of undefined

When calling my User.create method in my Sails.js app, I get the following error:
/Users/user/code/bt/tgein/node_modules/mongodb-core/lib/topologies/server.js:779
catch(err) { process.nextTick(function() { throw err}); }
Here is my User controller in its entirety.
User.create(req.params.all(), function userCreated(err, user) {
// var userid = user.id;
// console.log(userid);
if(err) {
console.log(err);
req.session.flash = {
err: err.ValidationError
}
return res.redirect('/user/loginDetails');
}
var oldDateObj = new Date();
var newDateObj = new Date(oldDateObj.getTime() + 60000);
req.session.cookie.expires = newDateObj;
req.session.authenticated = true;
console.log(req.session);
// res.redirect('/user/profileSelection/?id=' + user.id);
// Saves user data into session variable
req.session.user = user;
res.redirect('/user/profileSelection/');
});
apparently the session value is undefined for the request. This seems symptomatic of something basic that isn't happening, but I don't know what that is.
req.session.cookie is not defined and you are trying to set a value to an undefined object.
var oldDateObj = new Date();
var newDateObj = new Date(oldDateObj.getTime() + 60000);
if(!req.session.cookie)
req.session.cookie = {};
req.session.cookie.expires = newDateObj;
I think the problem is not of session, as session is always retained/defined within an sails app. May be the issue exists, when you trying to save the data.
The problem was I had the session store trying to go through the production adapter in my sessions.js on my local app, which caused the req.session to fail.

Baasbox and Javascript

I'm trying BaaSbox, a free Backend as a Service. But it has no out-of-the-box Javascript support I can use right away (yet, only iOS and Android)
I'm having trouble sending the right curl command from javascript, anyone happen to know a good resource or a simple working $.ajax template? I've tried a few examples from stackoverflow, but none of them specifically aimed at BaaSbox.
I've tried following the Java instructions on their site here. Just making a simple login work, but I keep getting the wrong responses from the server.
Or on the other hand, anyone know a good, free alternative to BaaSbox? I just want to be able to install it on my own server, no paid plans or whatever.
in the download page there is a preliminary version of the JS SDK (added few days ago).
The documentation is on the way, however in the zip file you can find a simple example.
For example to perform a signup:
//set the BaasBox parameters: these operations initialize the SDK
BaasBox.setEndPoint("http://localhost:9000"); //this is the address of your BaasBox instance
BaasBox.appcode = "1234567890"; //this is your instance AppCode
//register a new user
BaasBox.createUser("user", "pass", function (res, error) {
if (res) console.log("res is ", res);
else console.log("err is ", error);
});
Now you can login into BaasBox
//perform a login
$("#login").click(function() {
BaasBox.login("user", "pass", function (res, error) {
if (res) {
console.log("res is ", res);
//login ok, do something here.....
} else {
console.log("err is ", error);
//login ko, do something else here....
}
});
Once the user is logged in he can load the Documents belonging to a Collection (the SDK automatically manages the Session Token for you):
BaasBox.loadCollection("catalogue", function (res, error) { //catalogue is the name of the Collection
if (res) {
$.each (res, function (i, item) {
console.log("item " + item.id); //.id is a field of the Document
});
} else {
console.log("error: " + error);
}
});
However under the hood the SDK uses JQuery. So you can inspect it to know how to user $.ajax to call BaasBox.
For example the creatUser() method (signup) is:
createUser: function (user, pass, cb) {
var url = BaasBox.endPoint + '/user'
var req = $.ajax({
url: url,
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({
username: user,
password: pass
}),
success: function (res) {
var roles = [];
$(res.data.user.roles).each(function(idx,r){
roles.push(r.name);
})
setCurrentUser({"username" : res.data.user.name,
"token" : res.data['X-BB-SESSION'],
"roles": roles});
var u = getCurrentUser()
cb(u,null);
},
error: function (e) {
cb(null,JSON.parse(e.responseText))
}
});
}

Mongoose + Everyauth weird behavior

Using everyauth, when I login with a never autenticated before user on my website, the following code is launched. Checks if the user is already in my mongodb, if not it writes it. The issue right now is that works for the first authenticated user, then if a second user logins, my joiningUser._id parameters is properly initiated, but all the other parameters of my schema are from the first ever saved user, its like my parameters are never reinitialised... weird, my console.log shows the right new parameters, and not what is actually written in the database. My authentication is done via the everyauth module, I use the express framework.
exports.findOrCreateFacebookUser = function(fbUserData, promise){
User.findOne({_id:fbUserData.id}, function(err, user) {
if(err) {
console.log("Error in finding user for auth. Check Db");
promise.fail(err);
return;
}
else if(user){
console.log("User found ");
promise.fulfill(user);
}
else{
var joiningUser = new User();
joiningUser._id = fbUserData.id;
joiningUser.firstName = fbUserData.first_name;
joiningUser.lastName = fbUserData.last_name;
joiningUser.email = fbUserData.email;
//console.log(JSON.stringify(joiningUser));
joiningUser.save(function(err){
if(err){
console.log("Couldnt save new user: " + err);
promise.fail(err);
return;
}
else{
console.log("User wasnt existant, it is now created: " + JSON.stringify(joiningUser));
promise.fulfill(joiningUser);
}
});
}
});
};
Use mongoose-auth. It takes care of the combination of mongoose and everyauth for you.
There seems to be an issue with assigning _id with a forced value. So I created another id for the profile specific id (ex: facebookId).