Skip to content

Instantly share code, notes, and snippets.

@tarlepp
Forked from billyshena/gist:ec3829cfa2c5f78c8e66
Last active August 29, 2015 14:08
Show Gist options
  • Save tarlepp/ee9e655ac5fa5076c36b to your computer and use it in GitHub Desktop.
Save tarlepp/ee9e655ac5fa5076c36b to your computer and use it in GitHub Desktop.
/** 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 exec(error, team) {
if (error) {
return sails.services['errorservice'].sendError(404, error, 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
var processUser = function processUser(user, callback) {
// In parallel, we need to add each file & folder (from the arrays declared above)
async.parallel(
[
/** Add file association to each user **/
function fileJob(next) {
async.each(
files,
function addAssociationFor(file, done) {
user.files.add(file);
user.save(done);
},
next
);
},
/** Add folder association to each user **/
function folderJob(next) {
async.each(
folders,
function addAssociationFor(folder, done) {
user.folders.add(folder);
user.save(done);
},
next
);
}
],
callback
);
};
var processUsers = function processUsers(result, callback) {
sails.models['user']
.findOne({id: result.id})
.populate('files')
.populate('folders')
.exec(function(error, user) {
if (error) {
callback(error);
} else {
processUser(user, callback);
}
});
};
async.each(
team.users, // Foreach user in this Team
processUsers,
function allDone(error) {
if (error) {
return ErrorService.sendError(404, error, 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