Unable to access user info object property - facebook chat api - javascript

I'm using Facebook chat api to create a simple cli script that will reply to messages that are sent to my facebook account. I'm trying to assign and get the user name and my name to use them inside the reply but they are always undefined. I think that the object property aren't assigned correctly. Is there a fix for this?
require('dotenv').config();
const fs = require('fs');
const fb = require('facebook-chat-api');
const path = require('path');
const appStateFile = path.format({ dir: __dirname, base: 'appstate.json' });
let currentUser = null;
if( !fs.existsSync(appStateFile) ){
//debug .env
console.log(process.env);
fb({email: process.env.FB_EMAIL, password: process.env.FB_PWD}, (err, api) => {
if(err){
return console.log(err);
}
console.log(api);
api.setOptions({
listenEvents: true
});
fs.writeFileSync(appStateFile, JSON.stringify(api.getAppState()));
let id = api.getCurrentUserID();
api.getUserInfo(id, (err, profile) => {
console.log(profile); // profile is logged correctly
currentUser = profile;
});
api.listenMqtt( (err, event) => {
if(err){
return console.log(err);
}
if(event.type === 'message'){
console.log(event.body)
api.getUserInfo(event.senderID, (err, user) => {
if(err){
return console.log(err);
}
console.log(user); // user object is logged correctly
api.sendMessage('...', event.threadID)
});
}
});
});
}else{
fb({appState: JSON.parse(fs.readFileSync(appStateFile))}, (err, api) => {
if(err){
return console.log(err);
}
console.log(api);
api.setOptions({
listenEvents: true
});
let id = api.getCurrentUserID();
api.getUserInfo(id, (err, profile) => {
console.log(profile);
currentUser = profile;
});
api.listenMqtt( (err, event) => {
if(err){
return console.log(err);
}
if(event.type === 'message'){
console.log(event.body)
api.getUserInfo(event.senderID, (err, user) => {
if(err){
return console.log(err);
}
console.log(user)
api.sendMessage(`FB Pager v1.0.\nHi ${user.name}!Your message was forwarded with an email to ${currentUser.name}.`, event.threadID)
});
}
});
});
}

I think the problem here is that api.getUserInfo is asynchronous.
So you would need to nest them to get it to work.
Or you can try this, since getUSerInfo allows you to add an array of user ids to get the data for:
api.listenMqtt((err, event) => {
if (err) {
return console.log(err);
}
if (event.type === "message") {
const currentUserId = api.getCurrentUserID();
const senderId = event.senderID;
api.getUserInfo([currentUserId, senderId], (err, ret) => {
if(err) return console.error(err);
// Ret should contain the two users
// See: https://github.com/Schmavery/facebook-chat-api/blob/master/DOCS.md#getUserInfo
console.log(ret);
});
}
});
Nesting user calls method:
api.listenMqtt((err, event) => {
if (err) {
return console.log(err);
}
if (event.type === "message") {
let currentUserId = api.getCurrentUserID();
api.getUserInfo(currentUserId, (err1, signedInUser) => {
if (err1) {
return console.log(err);
}
api.getUserInfo(event.senderID, (err2, userInMessage) => {
if (err2) {
return console.log(err);
}
console.log(signedInUser, userInMessage)
api.sendMessage("...", event.threadID);
});
});
}
});

After a lot of debug I've found the correct way to access the needed informations. Since the user informations after that are retrived are mapped to another object that is the userId, the only way to access to each property is to use a for loop. Initially I was thinking that this can be avoided but unfortunately it's necessary otherwise using only dot notation will result in undefined. This is how I've solved
api.getUserInfo(userId, (err, user) => {
let username;
if(err){
return console.log(err);
}
for(var prop in user){
username = user[prop].name;
}
api.sendMessage(`Hello ${username!}`, event.threadID);
});

Related

Node Js: Remove string array element from mongoDB

I have a user schema as follows:
const UserSchema = new mongoose.Schema({
skills: [String]
});
module.exports = mongoose.model("User", UserSchema);
And a Fetch request to delete a skill as follows:
const deleteItem = async (id) => {
try {
await fetch(`http://localhost:5000/api/user/deleteskill`, {
method: "DELETE",
headers: { "Content-Type": "application/JSON", token: accessToken },
body: JSON.stringify({ userid: userid , skill:id}),
})
.then((res) => res.json())
.then((data) => {
console.log("USER SKILLS:", data.userskills);
});
} catch (err) {
console.log(err);
}
};
Server
const deleteSkill = async (req, res) => {
try {
const user = await User.findById(req.body.userid)
//user.skills.pull(req.body.skill);
// removeskill = user.skills.filter(function(item) {
// return item !== req.body.skill
// })
if (user.skills.includes(req.body.skill)) {
res.status(400).json("Item Still Exists");
} else {
res.status(200).json("Item Deleted");
}
} catch (error) {
res.status(500).send({ error: error.message });
}
};
the array is in the following structure
[
'skill1', 'java', 'skill5'
]
I have tried to remove the user skill from the array in several ways but I still get res.status(400).json("Item Still Exists");. What I'm doing wrong?
Use the findOneAndUpdate method to find a document with the user id and update it in one atomic operation:
const deleteSkill = async (req, res) => {
try {
let message = "Item Deleted";
let status = 200;
const user = await User.findOneAndUpdate(
{ _id: req.body.userid },
{ $pull: { skills: req.body.skill } },
{ new: true }
)
if (user && user.skills.includes(req.body.skill)) {
message = "Item Still Exists";
status = 400;
} else if (!user) {
message = "User Not Found";
status = 404;
}
res.status(status).send({ message });
} catch (error) {
res.status(500).send({ error: error.message });
}
};
I believe you want to remove skills from the database then the following function could help you out.
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var myquery = { userid: userid, skillid: skillid};
dbo.collection("skills").deleteOne(myquery, function(err, obj) {
if (err) throw err;
console.log("1 document deleted");
db.close();
});
});
You have a method of removing elements from arrays, if you want to remove the first one you could use array.shift (more on it here), but if you want to delete it completely from your database you could always, find it and then update it.
User.update({ _id: userid }, { $pull: { "skills": "[skill]" }})

How I exports a const outside another const using app.post? Express Javascript

I have a file signupResponse.js
const foundRegisterUser = function(err, foundUser){
if(!err){
console.log("Não tivemos erros")
if(!foundUser){
if(req.body.password == req.body.passwordConfirmation){
User.register({username: req.body.email}, req.body.password, function(err, user){
if (err){/
console.log(err);
} else {
console.log("Success")
res.render("welcome")
}
})
} else {
res.render("registerFailure",{msg0:MSG_INVALID_PASSWORD, msg1:"", msg2:""})
}
} else {
res.render("registerFailure",{msg0:MSG_INVALID_USER, msg1:"", msg2:"" })
}
} else {
res.render("registerFailure",{msg0:MSG_ERROR_REGISTER, msg1:"", msg2:""})
}
}
const signupresponse = (req, res) => {
Register.findOne({username: req.body.email}, function(err, foundUser){
if(!err){ /
if(!foundUser){
console.log("Usuário não encontrado")
res.render("registerFailure",{msg0:MSG_NOT_FOUND_REGISTER_0, msg1:MSG_NOT_FOUND_REGISTER_1, msg2:MSG_NOT_FOUND_REGISTER_2 })
}
else {
User.findOne({username: req.body.email},
foundRegisterUser(err, foundUser)
)
}
} else {
res.render("registerFailure",{msg0:MSG_ERROR_REGISTER, msg1:"", msg2:"" })
}
})
}
module.exports = signupresponse
I try to export to app.js
const signupResponse = require("./funcoes/signupResponse")
app.post("/signup", signupResponse)
This return ReferenceError: res is not defined
But when I put everything inside signupResponse and exports again, this works well:
const signupresponse = (req, res) => {
Register.findOne({username: req.body.email}, function(err, foundUser){
if(!err){
if(!foundUser){
console.log("Usuário não encontrado")
res.render("registerFailure",{msg0:MSG_NOT_FOUND_REGISTER_0, msg1:MSG_NOT_FOUND_REGISTER_1, msg2:MSG_NOT_FOUND_REGISTER_2 })
}
else {
User.findOne({username: req.body.email}, function(err, foundUser) {
if(!err){
console.log("Não tivemos erros")
if(!foundUser){
if(req.body.password == req.body.passwordConfirmation){
User.register({username: req.body.email}, req.body.password, function(err, user){
if (err){/
console.log(err);
} else {
console.log("Success")
res.render("welcome")
}
})
} else {
res.render("registerFailure",{msg0:MSG_INVALID_PASSWORD, msg1:"", msg2:""})
}
} else {
res.render("registerFailure",{msg0:MSG_INVALID_USER, msg1:"", msg2:"" })
}
} else {
res.render("registerFailure",{msg0:MSG_ERROR_REGISTER, msg1:"", msg2:""})
}
})
}
} else {
res.render("registerFailure",{msg0:MSG_ERROR_REGISTER, msg1:"", msg2:"" })
}
})
}
module.exports = signupresponse
The app works good and returns no errors.
I don't know how to use module.exports when has a lot of function to export.
How I export this signupResponse and put another function inside it without error?
Thanks!
It is not a problem of export, but a problem of scope of the ´´res´´ variable.
In the first code example, you have this error because you try to access the res object inside foundRegisterUser but this function doesn't know the res object. You define a res object in your other funtion signupresponse, ant the res object exist only inside of it. foundRegisterUserdoes not have any knowledge of it.
It works in your second example because you do not have a problem of scope for res in this case: everything is inside the same function and then your callback has access to
the res object.
One way to make your first example work would be to put the definition of foundRegisterUser inside signupresponse like this:
const signupresponse = (req, res) => {
const foundRegisterUser = function(err, foundUser){ ... };
Register.findOne({username: req.body.email}, function(err, foundUser){...
It would not be the prettiest, and would let plenty of room for structure improvement, but it should work.

Getting result from MySQL

My backend is consist of Api and DB. When I want to get response from DB I have had delayed output by 1 query.
API (I think api is ok. Start read DB first)
app.post('/api/query', (req, res) => {
console.log(`\n Query input : ${JSON.stringify(req.body)}`);
let queryInput = (Object.values(req.body).join(' '));
if(!dbApi.checkArray(queryInput)){ //If array is not made from clear strings
res.json(dbApi.queryFromUser(queryInput));
}
else{
res.json(dbApi.queryOutput);
}
});
app.listen(dbConfig.server.port, () =>
console.log(`Server running on port ${dbConfig.server.port}`));
DB
queryOutput = [];
const receivingQuery =(queryInput) => {
db.query(queryInput, (err, result) =>{
if(err) throw err+' : '+queryInput;
queryOutput = result;
console.log("\nQuery output "+ JSON.stringify(queryOutput)); //Output (result) is ok
});
return queryOutput //Here is Output from previous query (sends to API)
}
module.exports = {
queryOutput: queryOutput,
queryFromUser: receivingQuery,
}
I tryied callback method and I rewrite it couple of times. But I dont have enough skill to solve it.
If You want to return result of query so simply do following things:
add query method to db module:
function query(sql, args = []) {
return new Promise(function(resolve, reject) {
db.query(sql, args, (err, result) => {
if (err) return reject(err);
resolve(result);
});
});
}
// extra feature, getting user by id
async function getUserById(id) {
const result = await query('SELECT * FROM users WHER id = ? LIMIT 1', [id]);
if (Array.isArray(result) && result[0]) return result[0];
return null;
}
module.exports = {
query,
getUserById, // export user by id
queryOutput,
queryFromUser: receivingQuery,
}
use it (with async and await):
app.post('/api/query', async (req, res) => {
try {
console.log('Query input:', req.body);
const queryInput = Object.values(req.body).join(' ');
const result = await dbApi.query(queryInput);
res.json(result);
}
catch (error) {
console.error(error);
res.status(500).json({message: 'Please try again soon'});
}
});
app.get('/api/users/:id', async (req, res) => {
try {
const user = await dbApi.getUserById(req.params.id);
if (!user) return res.status(404).json({message: 'User not found'});
res.status(200).json(user);
}
catch (error) {
console.error(error);
res.status(500).json({message: 'Please try again soon'});
}
});
app.listen(dbConfig.server.port, () =>
console.log('Server running on port', dbConfig.server.port));

Passing a variable from ReactJS frontend to NodeJS back end using a GET route

I am working on a react app and am trying to find a way to pass a variable I define in my front-end (Question.js) to my back-end (server.js) so that I can issue different queries. I have the code
//Question.js
state = {
data: null
};
componentDidMount() {
this.callBackendAPI()
.then(res => this.setState({ data: res.express }))
.catch(err => console.log(err));
}
callBackendAPI = async () => {
const response = await fetch('/express_backend');
const body = await response.json();
if (response.status !== 200) {
throw Error(body.message)
}
return body;
};
//server.js
con.connect(function (err) {
if (err) throw err;
con.query("SELECT question FROM s1questions WHERE ID = 1", function (err, result, fields) {
if (err) throw err;
app.get('/express_backend', (req, res) => {
var x = JSON.stringify(result[0].question);
res.send({ express: `${x}` });
});
});
});
Your sever should probably split your database connection from your route handler definitions. Also, you could use query parameters to access questions based on their id in the database.
// question.js
callBackendAPI = async () => {
const response = await fetch(`/express_backend?questionId=1`);
const body = await response.json();
if (response.status !== 200) {
throw Error(body.message)
}
return body;
};
// server.js
app.get('/express_backend', (req, res) => {
const { questionId } = req.query;
// query database for question by id
});

Why is rows(callback) function from db.all returning undefined while rows is defined?

I'm calling a function to see if an email adress is in the db. It's either an empty or filled array. Whenever i return this value it is undefined afterwards. How can I solve this? Thanks in advance!
I have tried using next() and promises.
The function that calls the db query function.
const emailExists = async function(req,res,next){
let emailInDb = await usermodel.getOneByEmail(req, next);
console.log(emailInDb);
if(emailInDb.length !==0){
res.send('email already in use!');
}
else{
return next();
}
};
The db query.
const getOneByEmail = function (req, next){
let db = new sqlite3.Database(dbPath, (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to books db.');
});
db.all(`SELECT * FROM users WHERE email = ?`, [req.body.email],
(err, rows) => {
console.log(rows);
return rows;
});
};
console.log(emailInDb) gives undefined.
While console.log(rows) gives an array with results.
Putting await in front of a non async function does not magically make the function wait for the db-calls to resolve. You need to wrap the db-calls in a promise, e.g:
const getOneByEmail = (req, next) => {
return new Promise((resolve, reject) => {
let db = new sqlite3.Database(dbPath, (err) => {
if (err) {
console.error(err.message);
reject(err);
}
console.log('Connected to books db.');
});
db.all(`SELECT * FROM users WHERE email = ?`, [req.body.email],
(err, rows) => {
// TODO: check for error here and reject
console.log(rows);
resolve(rows);
});
});
};
Note that you shouldn't connect to the database each time you call getOneByEmail, instead reuse the connection...

Categories

Resources