Skip to content

Instantly share code, notes, and snippets.

@billyshena
Created October 23, 2014 16:33
Show Gist options
  • Save billyshena/ec3829cfa2c5f78c8e66 to your computer and use it in GitHub Desktop.
Save billyshena/ec3829cfa2c5f78c8e66 to your computer and use it in GitHub Desktop.
function
/** Context: We are going to create a sharebox system (an User has files & folder objects and can share it to his Team **/
// We have 4 models: File.js, User.js , Folder.js and Team.js
// 1) We first get the Team and we load the users in it
// 2) For each user, we need to add the association (User -> File and User->Folder)
// Loading the Team object
Team
.findOne(1)
.populate('users')
.exec(function (err, team) {
if (err) {
return ErrorService.sendError(404, err, req, res);
}
res.json(200);
var files = [1,2,9,22,23]; // Array containing some file ids as example
var folders = [1,2,32,21]; // Array containing some folder ids as example
async.each(
team.users, // Foreach user in this Team
function loadUser(result,callback){
User
.findOne({ id: result.id })
.populate('files')
.populate('folders')
.exec(function(err,user){
if(err){
callback(err);
}
else{
// In parallel, we need to add each file & folder (from the arrays declared above)
async.parallel(
[
/** Add file association to each user **/
function(cb){
async.each(
files,
function addAssociationFor(file,cbOne){
user.files.add(file);
cbOne();
},
function(err){
if(err){
cb(err);
}
else{
cb();
}
}
);
},
/** Add folder association to each user **/
function(cb){
async.each(
folders,
function addAssociationFor(folder,cbTwo){
user.folders.add(folder);
cbOne();
},
function(err){
if(err){
cb(err);
}
else{
cb();
}
}
);
}
],
function(err){
if(err){
callback(err);
}
else{
/** We save when all Files and Folders are added on the current user **/
user.save(function(err){
if(err){
callback(err);
}
else{
callback();
}
});
}
}
);
}
});
},
function(err){
if(err){
return ErrorService.sendError(404,err,req,res);
}
else{
return sails.log('Everything has been done here');
}
}
);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment