Ghost/core/server/models/base/utils.js
Hannah Wolfe 6a0f1cf231 Filter plugin with enforce/default logic
refs #5614, #5943

- adds a new 'filter' bookshelf plugin which extends the model
- the filter plugin provides handling for merging/combining various filters (enforced, defaults and custom/user-provided)
- the filter plugin also handles the calls to gql
- post processing is also moved to the plugin, to be further refactored/removed in future
- adds tests showing how filter could be abused prior to this commit
2015-11-17 10:39:44 +00:00

71 lines
2.6 KiB
JavaScript

/**
* # Utils
* Parts of the model code which can be split out and unit tested
*/
var _ = require('lodash'),
tagUpdate;
tagUpdate = {
fetchCurrentPost: function fetchCurrentPost(PostModel, id, options) {
return PostModel.forge({id: id}).fetch(_.extend({}, options, {withRelated: ['tags']}));
},
fetchMatchingTags: function fetchMatchingTags(TagModel, tagsToMatch, options) {
if (_.isEmpty(tagsToMatch)) {
return false;
}
return TagModel.forge()
.query('whereIn', 'name', _.pluck(tagsToMatch, 'name')).fetchAll(options);
},
detachTagFromPost: function detachTagFromPost(post, tag, options) {
return function () {
// See tgriesser/bookshelf#294 for an explanation of _.omit(options, 'query')
return post.tags().detach(tag.id, _.omit(options, 'query'));
};
},
attachTagToPost: function attachTagToPost(post, tag, index, options) {
return function () {
// See tgriesser/bookshelf#294 for an explanation of _.omit(options, 'query')
return post.tags().attach({tag_id: tag.id, sort_order: index}, _.omit(options, 'query'));
};
},
createTagThenAttachTagToPost: function createTagThenAttachTagToPost(TagModel, post, tag, index, options) {
return function () {
return TagModel.add({name: tag.name}, options).then(function then(createdTag) {
return tagUpdate.attachTagToPost(post, createdTag, index, options)();
});
};
},
updateTagOrderForPost: function updateTagOrderForPost(post, tag, index, options) {
return function () {
return post.tags().updatePivot(
{sort_order: index}, _.extend({}, options, {query: {where: {tag_id: tag.id}}})
);
};
},
// Test if two tags are the same, checking ID first, and falling back to name
tagsAreEqual: function tagsAreEqual(tag1, tag2) {
if (tag1.hasOwnProperty('id') && tag2.hasOwnProperty('id')) {
return parseInt(tag1.id, 10) === parseInt(tag2.id, 10);
}
return tag1.name.toString() === tag2.name.toString();
},
tagSetsAreEqual: function tagSetsAreEqual(tags1, tags2) {
// If the lengths are different, they cannot be the same
if (tags1.length !== tags2.length) {
return false;
}
// Return if no item is not the same (double negative is horrible)
return !_.any(tags1, function (tag1, index) {
return !tagUpdate.tagsAreEqual(tag1, tags2[index]);
});
}
};
module.exports.tagUpdate = tagUpdate;