Ghost/core/server/models/base/utils.js
Hannah Wolfe 7761873db7 Abstract findPage & add pagination Bookshelf plugin
closes #2896

- move default options / custom code into model functions
- move most of the filtering logic into base/utils.filtering (to be relocated)
- move the remainder of findPage back into base/index.js and remove from posts/users&tags
- move pagination-specific logic to a separate 'plugin' file
- pagination provides new fetchPage function, similar to fetchAll but handling pagination
- findPage model method uses fetchPage
- plugin is fully unit-tested and documented
2015-06-22 10:20:47 +01:00

51 lines
1.5 KiB
JavaScript

/**
* # Utils
* Parts of the model code which can be split out and unit tested
*/
var _ = require('lodash'),
filtering;
filtering = {
preFetch: function preFetch(filterObjects) {
var promises = [];
_.forOwn(filterObjects, function (obj) {
promises.push(obj.fetch());
});
return promises;
},
query: function query(filterObjects, itemCollection) {
if (filterObjects.tags) {
itemCollection
.query('join', 'posts_tags', 'posts_tags.post_id', '=', 'posts.id')
.query('where', 'posts_tags.tag_id', '=', filterObjects.tags.id);
}
if (filterObjects.author) {
itemCollection
.query('where', 'author_id', '=', filterObjects.author.id);
}
if (filterObjects.roles) {
itemCollection
.query('join', 'roles_users', 'roles_users.user_id', '=', 'users.id')
.query('where', 'roles_users.role_id', '=', filterObjects.roles.id);
}
},
formatResponse: function formatResponse(filterObjects, options, data) {
if (!_.isEmpty(filterObjects)) {
data.meta.filters = {};
}
_.forOwn(filterObjects, function (obj, key) {
if (!filterObjects[key].isNew()) {
data.meta.filters[key] = [filterObjects[key].toJSON(options)];
}
});
return data;
}
};
module.exports.filtering = filtering;