Ghost/core/server/models/plugins/has-posts.js
Daniel Lockyer 0cd9acabec
Imported Bookshelf type into plugin JSDocs
no issue

- the `Bookshelf` type wasn't being imported anywhere and editors were
  showing warnings for the missing type
- also fixes use of `Bookshelf.Model` - this doesn't work if we declare
  `Bookshelf` using a `@typedef` and the preferred syntax is using an
  array index
- note: it still complains because we're calling functions that are only
  declared in our custom Bookshelf Model but this is a step in the right
  direction
2021-06-14 16:30:58 +01:00

64 lines
1.9 KiB
JavaScript

const _ = require('lodash');
const _debug = require('ghost-ignition').debug._base;
const debug = _debug('ghost-query');
const addHasPostsWhere = (tableName, config) => {
const comparisonField = `${tableName}.id`;
return function (qb) {
return qb.whereIn(comparisonField, function () {
const innerQb = this
.distinct(`${config.joinTable}.${config.joinTo}`)
.select()
.from(config.joinTable)
.whereRaw(`${config.joinTable}.${config.joinTo} = ${comparisonField}`)
.join('posts', 'posts.id', `${config.joinTable}.post_id`)
.andWhere('posts.status', '=', 'published');
debug(`QUERY has posts: ${innerQb.toSQL().sql}`);
return innerQb;
});
};
};
/**
* @param {import('bookshelf')} Bookshelf
*/
const hasPosts = function hasPosts(Bookshelf) {
const modelPrototype = Bookshelf.Model.prototype;
Bookshelf.Model = Bookshelf.Model.extend({
initialize: function () {
return modelPrototype.initialize.apply(this, arguments);
},
fetch: function () {
if (this.shouldHavePosts) {
this.query(addHasPostsWhere(_.result(this, 'tableName'), this.shouldHavePosts));
}
if (_debug.enabled('ghost-query')) {
debug('QUERY', this.query().toQuery());
}
return modelPrototype.fetch.apply(this, arguments);
},
fetchAll: function () {
if (this.shouldHavePosts) {
this.query(addHasPostsWhere(_.result(this, 'tableName'), this.shouldHavePosts));
}
if (_debug.enabled('ghost-query')) {
debug('QUERY', this.query().toQuery());
}
return modelPrototype.fetchAll.apply(this, arguments);
}
});
};
module.exports = hasPosts;
module.exports.addHasPostsWhere = addHasPostsWhere;