0
Fork 0
mirror of https://github.com/TryGhost/Ghost.git synced 2025-02-10 23:36:14 -05:00
ghost/core/server/models/base/plugins/relations.js
Simon Backx a30e42404b
Added getLazyRelation model helper method (#14943)
closes https://github.com/TryGhost/Team/issues/1626

- getLazyRelation is a safer shorthand for `model.related('relationName').fetch()`
- prevents doing a `fetch` operation on a relation that is already loaded, which can cause issues when `formatOnWrite` has a custom implementation
- uses the already loaded relation if it exists, or loads the relation
- doesn't reload if already loaded
- reload is forceable using the forceRefresh option
2022-05-31 13:21:53 +02:00

30 lines
1.4 KiB
JavaScript

/**
* @param {import('bookshelf')} Bookshelf
*/
module.exports = function (Bookshelf) {
Bookshelf.Model = Bookshelf.Model.extend({
/**
* Return a relation, and load it if it hasn't been loaded already (or force a refresh with the forceRefresh option).
* refs https://github.com/TryGhost/Team/issues/1626
* @param {string} name Name of the relation to load
* @param {Object} [options] Options to pass to the fetch when not yet loaded (or when force refreshing)
* @param {boolean} [options.forceRefresh] If true, the relation will be fetched again even if it has already been loaded.
* @returns {Promise<import('bookshelf').Model|import('bookshelf').Collection|null>}
*/
getLazyRelation: async function (name, options = {}) {
if (this.relations[name] && !options.forceRefresh) {
// Relation was already loaded
return this.relations[name];
}
if (!this[name]) {
return undefined;
}
// Not yet loaded, or force refresh
// Note that we don't use .refresh on the relation on options.forceRefresh
// Because the relation can also be a collection, which doesn't have a refresh method
this.relations[name] = this[name]();
return this.relations[name].fetch(options);
}
});
};