Created
September 9, 2014 12:44
-
-
Save bodia-uz/9c6ea42e3c75b0dadada to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Create a project copy | |
*/ | |
exports.clone = function(req, res) { | |
var project = req.project.toObject(), | |
title = project.title, | |
prefix = 'Копия ', | |
postfix = '', | |
copyTitle = title.indexOf(prefix) === 0 ? title.replace(/ \(\d+\)$/,'') : prefix + title, | |
titlePattern = new RegExp('^' + escape(copyTitle) + '( \\(\\d+\\))?$'), | |
count = 0; | |
console.log('title pattern ', titlePattern); | |
Project | |
.find({title: titlePattern}) | |
.exec(function(err, projectCopies){ | |
if (err) return next(err); | |
var titles = projectCopies.map(function(p) { return p.title;}); | |
console.log('copies', titles); | |
// find unused copy name | |
while(titles.indexOf(copyTitle + postfix) !== -1){ | |
count++; | |
postfix = ' (' + count + ')'; | |
console.log('copyTitle', copyTitle + postfix); | |
} | |
// prepeare new project object | |
delete project['_id']; | |
// set copy title | |
project.title = copyTitle + postfix; | |
// set type as user own project | |
project.type = 0; | |
project = new Project(project); | |
console.log('clone name ', project.title); | |
project.save(function(err) { | |
if (err) { | |
console.log('an error ocurrend while project clone saving'); | |
return next(err); | |
} else { | |
console.log('project cloned'); | |
res.jsonp(project); | |
} | |
}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment