Skip to content

Instantly share code, notes, and snippets.

@Xananax
Last active October 21, 2015 20:28
Show Gist options
  • Save Xananax/666c7a876bdcbb8c7820 to your computer and use it in GitHub Desktop.
Save Xananax/666c7a876bdcbb8c7820 to your computer and use it in GitHub Desktop.
/**
* Creates or updates a group and attached files and sub-groups
* @param {Object} rethink object with {r,conn}
* @param {Object|String} mainGroup either a group name, or an object {id,name}
* @param {Array} files an array of files paths or an array of {id,path}
* @param {Array} groups an array of groups names or an array of {id,name}
* @param {Function} callback a nodeback with signature (err,results)
*
* This function creates or updates a group on the fly
* Examples:
*
* createGroup({r,conn},'groupA',['path/to/file'],['subGroupA','subGroupB'])
* will:
* - create the groups "groupA", "subGroupA", "subGroupB"
* - create the file "path/to/files"
* - establish relations between the files, groups, and the main group
*
*
* createGroup({r,conn},{id:1,name:'groupA'},['path/to/file'],['subGroupA',{id:3}])
* will:
* - create the group "subGroupA" (assuming the other two exist)
* - create the file "path/to/files"
* - establish relations between the files, groups, and the main group
*/
function createGroup({r,conn},mainGroup,files,groups,cb){
if(typeof mainGroup == 'string'){
mainGroup = {name:group};
}
if(empty(groups)){groups = false;}
if(empty(files)){files = false;}
groups = (groups && groups.map(group=>(typeof group == 'string'?{name:group}:group)).filter(Boolean)) || [];
files = (files && files.map(file=>(typeof file === 'string'?{path:file}:file)).filter(Boolean)) || [];
const groupsIds = (groups && groups.map(group=>(id in group)?group.id:false).filter(Boolean)) || [];
const filesIds = (files && files.map(file=>(id in file)?file.id:false).filter(Boolean)) || [];
var mainGroup_id = mainGroup.id ? mainGroup.id : false;
function insertGroups(mainGroup_id){
return r.branch(
groups
, r.table('group_groups').insert(
r.args(
r.table('groups')
.insert(groups)('generated_keys')
.add(groupsIds)
.map(id=>{parent_id:mainGroup_id,child_id:id})
)
)
, 0
)
}
function insertFiles(mainGroup_id){
return r.branch(
groups
, r.table('group_files').insert(
r.args(
r.table('files')
.insert(files)('generated_keys')
.add(filesIds)
.map(id=>{group_id:mainGroup_id,file_id:id})
)
)
, 0
)
}
function insertRelated(mainGroup_id){
return r
.do(mainGroup_id,insertGroups)
.do(mainGroup_id,insertFiles)
}
(mainGroup_id ?
r.do(maingroup_id,insertRelated) :
r.table('groups').insert(mainGroup)('generated_keys').do(insertRelated)
).run()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment