更新时间:2023-01-12 08:38:35
我在服务中编写了一个自定义(更新的)函数以及一个助手:
I wrote a custom (updated) function along with a helper in a service:
/*
* Add multiple objects to a relationship
* @param {object} origin The object which hold the items
* @param {array} data The new list to be inserted
* @param {string} relation name of the relationship, for instance 'cats'
*/
exports.updateManyRelations = function(origin, data, relation){
//Destroy all old connections
return origin[relation].destroyAll().then(function(response){
//All were deleted and nothing to add
if(!data || data.length == 0){return [];}
//We have a list to go through, do the dirty work!
return addMultipleRelationsToObject(origin[relation], data, []);
}).then(function(newList){
// new items created
return newList
}, function(error){
console.log(error);
});
}
/*
* Helper function to add multiple related objects to a object in a correct promise chain
*/
var addMultipleRelationsToObject = function(objectRelation, list, newList){
if(list && list.length == 0){return Promise.resolve(newList);}
var item = list.pop();
if(!objectRelation.hasOwnProperty("add")){
return Promise.reject("Relationship is wrong for: " + objectRelation);
}
return objectRelation.add(item.id).then(function(newlyAdded){
newList.push(item);
return addMultipleRelationsToObject(objectRelation, list, newList);
});
}