Handled duplicated authors

no issue

- discovered while testing
- the matching helper can fallback twice to owner user in theory
This commit is contained in:
kirrg001 2019-02-18 19:30:11 +01:00
parent a575f85af7
commit 3b2ede88e0

View File

@ -228,6 +228,13 @@ module.exports.extendModel = function extendModel(Post, Posts, ghostBookshelf) {
return attrs; return attrs;
}, },
/**
* Authors relation is special. You cannot add new authors via relations.
* But you can for the tags relation. That's why we have to sort this out before
* we trigger bookshelf-relations.
*
* @TODO: Add a feature to bookshelf-relations to configure if relations can be added or should be matched only.
*/
matchAuthors(model, options) { matchAuthors(model, options) {
let ownerUser; let ownerUser;
const ops = []; const ops = [];
@ -243,6 +250,7 @@ module.exports.extendModel = function extendModel(Post, Posts, ghostBookshelf) {
ops.push(() => { ops.push(() => {
const authors = model.get('authors'); const authors = model.get('authors');
const authorsToSet = [];
return Promise.each(authors, (author, index) => { return Promise.each(authors, (author, index) => {
const query = {}; const query = {};
@ -260,16 +268,18 @@ module.exports.extendModel = function extendModel(Post, Posts, ghostBookshelf) {
.where(query) .where(query)
.fetch(Object.assign({columns: ['id']}, _.pick(options, 'transacting'))) .fetch(Object.assign({columns: ['id']}, _.pick(options, 'transacting')))
.then((user) => { .then((user) => {
authors[index] = {}; let userId = user ? user.id : ownerUser.id;
if (!user) { // CASE: avoid attaching duplicate authors relation
authors[index].id = ownerUser.id; const userExists = _.find(authorsToSet, {id: userId.id});
} else {
authors[index].id = user.id; if (!userExists) {
authorsToSet[index] = {};
authorsToSet[index].id = userId;
} }
}); });
}).then(() => { }).then(() => {
model.set('authors', authors); model.set('authors', authorsToSet);
}); });
}); });