Callback is not a function in nodejs - javascript

I am trying to implement classMethods of a sequelize model for authentication.
authenticate: function(password, callback) { // authenticate a given login body
bcrypt.compare(password, this.password_hash, function (err, isMatch) {
if (err) return callback(err);
callback(null, isMatch);
});
},
When I try to run the above codes, the command said "callback is not a function".

How are you calling authenticate? Make sure when you write your callback as a parameter you don't use parentheses. So make sure you do 'authenticate(foo,bar)' instead of authenticate(foo,bar())'

Related

RethinkDB - Run query one after another

I am having trouble running multiple queries inside a single connection with RethinkDB. I have tried the r.do as seen in this question, however no success. I have also tried working with the conditional update queries. What I am looking to do is:
Open the connection.
Query to see if my field is there and if it is, perform some tasks.
Query to see if a counts field is there, subtract it by one.
What would be the best way to go about this? It seems I might be missing something?
r.connect(config.rethinkdb, function(err, conn) {
if (err) {
throw err;
}
else {
console.log('Connected.');
app.set('rethinkdb.conn', conn);
}
r.table('upcs').filter({AcceptedUPC:data}).run(conn, (err, cursor) => {
if (err) throw err;
console.log(data);
cursor.toArray((err,resu) => {
if (err) throw err;
//make a csv with some information
})
})
And in the same connection run
r.table('upcs').filter({AcceptedUPC:data}).filter(r.row.hasFields("UPCCount")).update({UPCCount: r.row("UPCCount").sub(1)}).run(conn, (err,cursor) => {
if (err) throw err;
});
Running this in NodeJS
I'm going to assume you are using this library for node.
You can that they actually allow you to do either callbacks or promises. I would recommend promises to avoid brackets of hell.
For promises you can use the bluebird library to make life easy.
You can do it by doing the following.
r.connect(config.rethinkdb).then(() => {
console.log("Connected");
app.set("rethinkdb.conn", conn);
return r.table('upcs').filter({AcceptedUPC:data}).run(conn);
}).then((cursor) => {
console.log(data); //maybe this should be cursor but I don't use rethinkDB
return cursor.toArray();
}).then((resu) => {
//make a csv with some information
}).catch((err) => {
throw err;
});

nodejs/pg, callback parameters

I am fairly new to node.js, and haven't done much of javascripts. Tried to search my problem, but couldn't find specific answer related to it.
So, while I was working on attaching the PostgreSQL to my app, I followed a snippet from some example on web, and it seems like working pretty well.
Anyways I wanted to understand how it works, I had a problem understanding specific part of the following code:
module.exports = {
query: function(text, values, cb) {
pool.connect(function(err, client, done) {
if(err) {
return console.error('error fetching client from pool', err);
}
console.log(client);
client.query(text, values, function(err, result) {
done();
cb(err, result);
})
});
}
}
and the specific part is:
pool.connect(function(err, client, done) { ... }
What I understood is connect function takes callback function with err, client, and done as parameter, however I couldn't understand from where the function(err, client, done) is passed to connect function as parameter. By where, I mean an object or a caller that call connect function.
I had suspected that it would be handled internally, but I wanted to know clearly.
Bydefault all callback function, the first parameter must be an error and second will be a result of ur callback function.
Done is similar to callback keyword, which says, your task is over and give response back from where the function has called, its just like return statement in normal function
example:
function callbackDemo(arg1, arg2, callback) {
if (condition)
callback(null, "Success");
else
callback("error");
}
callbackDemo(1, 2, function(err, result){
if(!err)
console(result);
else
console.log(err);
});

What is "done" callback function in Passport Strategy Configure "use" function

I'm an node.js and express.js noob. This question may seems silly but I'm really in confusion.
I'm trying to configure Local Strategry authentication by using passport. As shown in the official documentation, we can figure this Local Strategy by the following code,
passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({ username: username }, function (err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false); }
if (!user.verifyPassword(password)) { return done(null, false); }
return done(null, user);
});
}
));
My confusion is about the done callback function. When the official docs show this local strategy using as a middleware in the route handler, there is no need to pass the function parameter for this done callback.
app.post('/login',
passport.authenticate('local'),
function(req, res) {
res.redirect('/');
});
So, isn't this done callback function will be null if we don't provide the function parameter? If not, what is that done callback function and what processes will be happening in this done callback function?
done is a method called internally by the strategy implementation.
Then it navigates you, as you can see, to one of the success / error / fail methods (again, by the implementation. there are more options).
Each of these options may calls to the next, where in your snippet code is the following:
function(req, res) {
res.redirect('/');
});
When success is called, it can attach the user to the request or do other things, depending on your needs (it looks for the options you pass to passport.authenticate). If you want to determine when next will be called, you should use custom callback which gives you more flexibility.
I strongly recommend that you read the source.
It's now 2022 and I had the same question. The passport documentation has improved and it describes the done method (also called cb) here: https://www.passportjs.org/concepts/authentication/strategies/#verify-function. You will need to call this yourself in your strategy's verify function.
A verify function yields under one of three conditions: success, failure, or an error.
If the verify function finds a user to which the credential belongs, and that credential is valid, it calls the callback with the authenticating user:
return cb(null, user);
If the credential does not belong to a known user, or is not valid, the verify function calls the callback with false to indicate an authentication failure:
return cb(null, false);
If an error occurs, such as the database not being available, the callback is called with an error, in idiomatic Node.js style:
return cb(err);

How do I call MySql procedures from Node JS

I want to call a stored procedure from MySql node:
How do I call it? The documentation says:
You can call stored procedures from your queries as with any other mysql driver. If the stored procedure produces several result sets, they are exposed to you the same way as the results for multiple statement queries
I tried searching for it on internet but got very old results which do not work anymore.
I tried:
connection.query('procedure_name()', {84,Bhuwan}, function(err, result) {
connection.destroy();
if (err)
throw err;
callback(err, result);
});
But I am getting error.
Can anyone provide a proper syntax for it??
You have to use 'call' command and if you have parameters to pass to the query, you need to add '?' marks. Check the code.
connection.query("call procedure_name(?,?)", [param1, param2], function (err, result) {
if (err) {
console.log("err:", err);
} else {
console.log("results:", result);
}
});

Node.js - Break out of callback function and return true/false in the parent functon

I'm using the Node Express framework to build an API and I run into a problem regarding the Basic Auth functionality. I need to run an SQL query to retrieve information about a user and validate their credentials. The issue occurs after the query has been completed. The SQL data is sent into a callback function as shown below. I want to do all the validation inside that callback but I want to break out of the SQL callback and return true/false from the express.basicAuth() function. I have tried setting a global variable and then accessing it outside of the SQL callback but sometimes the query might not have finished by the time that it gets the block that accesses that global variable. Thanks in advance for your help.
var auth = express.basicAuth(function(user, pass) {
// Query to select information regarding the requested user
/* Query here to find the requested user's data */
client.query(query, function (err, rows, fields) {
if (err) throw err;
GLOBAL.sql = rows;
/* I want to break out of this query callback function and return true from this auth variable */
});
// Sometimes the query isn't completed when it gets to this stage
console.log(JSON.stringify(GLOBAL.sql));
});
express.basicAuth also supports asynchronous operation:
var auth = express.basicAuth(function(user, pass, next) {
...
client.query(query, function (err, rows, fields) {
if (err)
next(err);
else
if (/* authentication successful */)
next(null, user); // <-- sets 'req.remoteUser' to the username
else
next(null, false);
});
});

Categories

Resources