Improving node.js code (sequelize, promises and passport)

I'm a newbie in node.js, sequelize, Bluebird promises and FB authentication.

I'd like to persist my FB authenticated user with some authentication details.

In my model, one user can have many authentications at the same time (one for the browser, another for the mobile, etc). I need to take care of these authentications, so I have the next relationships:

User.hasMany(Auth); Auth.belongsTo(User);

I wrote this code that works, but i'm still looking for an smarter solution.

The main goal is to add the authentication information to the user. So, before peristing the auth info, I look for a persisted user.

function(accessToken, refreshToken, profile, done) { console.log("FacebookStrategy_function:\naccessToken: " + accessToken); var thatUser=null; User.find({ where: { username: profile.username }, include: [{model: Auth}] }).then(function(user) { console.log("USER IS #1: %j", user); if(user!= null){ // User found in database console.log("User " + profile.id + "found in database"); return user; }else{ // First time that user authenticate in app var user = User.build({ username: profile.username, givenName: profile.name.givenName, familyName: profile.name.familyName }); return user.save(); } }).then(function(user) { console.log("USER IS #2: %j", user); thatUser=user; var auth= Auth.build({ provider: 'facebook', providerId: profile.id, accessToken: accessToken }); return user.addAuth(auth); }).then(function(auth){ user=thatUser; console.log("USER IS #3: %j", user); console.log("done. user and association saved. auth is: %j", auth); done(null, user); // Call FacebookEstrategy's done }, function(err) { console.log("\nsomething happened persisting user/auth " + err); done(err, null); // Propagate error to FacebookEstrategy }); }

Having the next log:

FacebookStrategy_function: accessToken: CAACO... Executing (default): SELECT "Users".*, "Auths"."id" AS "Auths.id", ... WHERE "Users"."username"='john.doe'... INSERT INTO "Users" ("id","username","givenName","familyName","createdAt","updatedAt") VALUES (DEFAULT,'john.doe',...) USER IS #1: null Executing (default): INSERT INTO "Users" ("id","username","givenName","familyName","createdAt","updatedAt") VALUES (DEFAULT,'john.doe',...) USER IS #2: {"username":"john.doe","givenName":"John","familyName":"Doe","id":2,"updatedAt":"2014-11-09T19:12:23.250Z","createdAt":"2014-11-09T19:12:23.250Z"} Executing (default): SELECT * FROM "Auths" WHERE "UserId" = 2; Executing (default): INSERT INTO "Auths" ("id","provider","providerId","accessToken","createdAt","updatedAt","UserId") VALUES (DEFAULT,'facebook','...','CAACO...','2014-11-09 19:12:23.278 +00:00','2014-11-09 19:12:23.278 +00:00',2) RETURNING *; USER IS #3: {"username":"john.doe","givenName":"John","familyName":"Doe","id":2,"updatedAt":"2014-11-09T19:12:23.250Z","createdAt":"2014-11-09T19:12:23.250Z"} done. user and association saved. auth is: {"provider":"facebook","providerId":"...","accessToken":"CAACO...","id":2,"UserId":2,"updatedAt":"2014-11-09T19:12:23.278Z","createdAt":"2014-11-09T19:12:23.278Z"}

For me was to wierd to handle, that user.addAuth(auth) return an auth object. In the next then method, I expected to receive an user object (instead of auth) As workaround, I used in the main function scope an awful thatUser variable. Is there any smarter way to do that?

In logs, the trace "USER IS #3:" is showing an user without its authentications objects. Why?

Any correction or improvement will be wellcomed

Thanks

-------------Problems Reply------------

If you're using promises - you can drop the done callback - you can simply return the promise. If you really want the done callback - you can call .nodeify instead of explicitly calling it although returning promises has other benefits like unhandled rejection tracking.

You can also use aggregation methods instead of explicit closure scope:

function(accessToken, refreshToken, profile) {
console.log("FacebookStrategy_function:\naccessToken: " + accessToken);
return User.find({
where: { username: profile.username }, include: [{model: Auth}]
}).then(function(user) {
console.log("USER IS #1: %j", user);
if(user!= null){ // User found in database
console.log("User " + profile.id + "found in database");
return user;
}
return User.build({ // first time
username: profile.username,
givenName: profile.name.givenName,
familyName: profile.name.familyName
}).save();
}).then(function(user) {
console.log("USER IS #2: %j", user);
var auth= Auth.build({
provider: 'facebook',
providerId: profile.id,
accessToken: accessToken
});
return [user, user.addAuth(auth)]; // note the array
}).spread(function(user, auth){ // note the spread
console.log("USER IS #3: %j", user);
console.log("done. user and association saved. auth is: %j", auth);
return user;
});
}

Now, if I'm allowed to drop all the console.logs, this gets much shorter:

function(accessToken, refreshToken, profile) {
return User.find({
where: { username: profile.username }, include: [{model: Auth}]
}).then(function(user) {
return user || User.build({ // first time
username: profile.username,
givenName: profile.name.givenName,
familyName: profile.name.familyName
}).save();
}).then(function(user) {
return Auth.build({
provider: 'facebook',
providerId: profile.id,
accessToken: accessToken
}).return(user);
});
}

Category:node.js Views:1 Time:2014-11-09

Related post

  • About Node's code style 2012-04-23

    EDIT thx to all the answers, and finally I decide to use some tools like Step, all I need is "flow control" and don't want any thing else which may slow down the performance (I don't know how much exactly it would effect or the effect just can be ign

  • Is it rude to refactor/improve team members' code? 2009-07-01

    When working on a single project with a small team, say, three developers, it's common for us to ask each other: "Oh, how does this class work?" or "What property do I set on this to make this happen?" as the code base grows, and of course, we must m

  • How can I improve this PHP code? 2009-08-17

    I have the php code below which help me get a photo's thumbnail image path in a script It will take a supplied value like this from a mysql DB '2/34/12/thepicture.jpg' It will then turn it into this '2/34/12/thepicture_thumb1.jpg' I am sure there is

  • Deploying updates to production node.js code 2010-10-16

    This may be a basic question, but how do I go about effeciently deploying updates to currently running node.js code? I'm coming from a PHP, JavaScript (client-side) background, where I can just overwrite files when they need updating and the changes

  • How do i improve the legacy code implementation, Response.Redirect? 2010-11-19

    Some scenarios to ponder. There is a legacy code which has following implementation Example1 and Example2. If we try to implement MSDN recommendation then the legacy code fails. Here is a Legacy code example: Example 1: void Page_Load() { .... some c

  • Updating with modifier operators in the Mongo CLI works but not from node.js code using mongoose 2011-06-02

    Connecting to our Mongo instance using the CLI, you can use the update modifier operators just fine: db.users.update({nickname: 'mcoalson'}, { "$addToSet" : { room_ref : "b"}}) db.users.update({nickname: 'mcoalson'}, { "$addToSet" : { room_ref : "c"}

  • How to improve the following code in Objective-C? 2011-08-30

    I have the following code that displays the alerts depending on the result: How can I improve the following code: -(IBAction)saveSettings:(id)sender { UIAlertView *alert = nil; username = self.usernameTextField.text; token = self.passwordTextField.te

  • sharepoint 2010 cannot get global navigation nodes in code 2011-11-30

    I have sharepoint site and i want read in code global navigation information. On properties page: /_layouts/AreaNavigationSettings.aspx I added "location","organization","98" nodes. But when i am trying to get those nodes in code using (var site = ne

  • How to make a page recognize node.js code 2012-03-05

    I´ve tried socket.io to create a tiny chat. But now, I´m tring to do the same thing without any dependencies. My server side seems to be OK, the problem is to render my html page when the browser doesn´t recognize any node.js code, e.g: "require" sta

  • Improving the lambda-code OCaml generates for assertions 2012-04-04

    I would like to improve the lambda-code generated for the "assert" OCaml 3.12.1 construct. Here is an example: let f x = assert (x = 4); assert (2 + x = 6); assert (x - x = 0); exit x The file longfilename.ml above is representative of large OCaml mo

  • "average length of the sequences in a fasta file": Can you improve this Erlang code? 2010-07-21

    I'm trying to get the mean length of fasta sequences using Erlang. A fasta file looks like this >title1 ATGACTAGCTAGCAGCGATCGACCGTCGTACGC ATCGATCGCATCGATGCTACGATCGATCATATA ATGACTAGCTAGCAGCGATCGACCGTCGTACGC ATCGATCGCATCGATGCTACGATCTCGTACGC >titl

  • Improving a tooltip code 2008-10-31

    I'm trying to build a hoverable Jquery tooltip. This tooltip should appear when I hover over some element, and stay put if I choose to hover over the tooltip itself too. The tooltip should disappear only if I hover away from the original element or f

  • Improving quality of code in CakePHP 2009-07-03

    I have been using CakePHP for a few weeks now and its been an great experience. I've managed to port a site surprisingly quickly and I've even added a bunch of new features which I had planned but never got around to implementing. Take a look at the

  • How to improve the following code in PHP 2009-07-10

    Here is a simple form I am using to send XML data in admin_xml.php <form name="review" action="admin_xml.php" method="post"> <textarea name="xml" cols="40" rows="10"></textarea> <input class="submit" type="submit" value="Submit R

  • How do I improve this Menu code 2009-07-31

    I am using a function to spit out my main and sub menu's for me. Basically I feed it a page ID and it gives me the menu with the menu item properly highlighted through CSS. What I'm asking is: How do I improve this code (and others like it that I hav

  • How can I improve my PHP code to make it more efficient? 2009-12-10

    I've written a simple PHP script which checks if a random value is a valid Rugby Union score. It works quite nicely but isn't particularly efficient, any advice on improving it would be most welcome. $score = rand(0, 60); /* Rugby Union * * Try = 5 p

  • Improve property monitoring code? 2010-02-13

    I made a utility debug class in a C# game I'm working on to be able to monitor and watch values of properties. Goes like this: public static class Monitor { private static List<object> monitoredObjects; public static void Initialize() { monitor

  • how to write clean code in c# language and improve quality of code 2010-04-27

    how i can improve our code quality and write clean code. if i write a unclean ugly code then how i can migrate as a good code (beautiful and clean). --------------Solutions------------- Everyone finds it's own way of what clean code means, BUT there

  • Help improve this Javascript code? 2010-05-04

    EDIT2: I omitted the line that updates the UI "urrentNode.set_checked(checked);", and it run amazingly fast. Apparently this is the reason of that performance bottleneck, what do you guys suggest? Hello SO, In short, I'm dealing with Telerik's RadTre

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.174 (s). 11 q(s)