Reputation: 1933
Could anyone please help me understand a this part of code:
var auth = function(cb) {
return _.wrap(cb, function(fn, data) {
redis.get(email, function(err, id){
if (!err) throw err;
if (!id) return socket.disconnect('unauthorized');
fn(data);
});
});
};
that I got from this article.
I don't understand what's happening there, even though I navigated to the lodash documentation and read about 'wrap' method. I'm confused, especially because I can't see where in the article this 'auth' is further used! (I think that is defined to be used somewhere after all). Thank you in advance.
Upvotes: 0
Views: 154
Reputation: 10672
So, let's break that down. First, we are assigning a function that takes a cb
parameter to auth
. What does that function do, well, it returns the result of _.wrap
. Looking at the docs, _.wrap
is a currying function, so it takes an arg (cb
) and a function, and returns a new function where the first parameter is bound to the arg, and the rest of the parameters are unbound. In fact, the _.wrap
part:
return _.wrap(cb, function(fn, data) {
/* code */
fn(data); // inside of the redis scope
})
is probably overkill, since you are in a closure from the outer function, so you could just do:
return function(data) {
/* code */
cb(data) // in the redis callbak scope, but that is still in the closed over scope
}
I'm honestly not sure why they didn't just do that (hammer/nail?).
Let's go on.
So, we've determined that auth
is a function that takes a cb
parameter and returns a function that takes a data
parameter. That function is now calling redis.get
to find the value associated with the key stored in email
(which is pulled in from the surrounding scope). It then calls the passed in callback function (the one taking an err and id) validates the parameters (disconnecting the websocket if the email isn't associated in redis, and finally calls the orginal cb
callback with the passed in data
parameter.
I'm not sure where it is used in the code, but the idea is that you can call it as:
let authCb = auth((data) => { console.log(data) })
authCb('test')
and if the email is found in redis, then test
should be logged to the console. In the context of the article, you would use this to validate the connection before you actually started communicating with the socket (in the cb
function)
Upvotes: 1