Added 'getDefaultProduct' convenience method to product repo

refs https://github.com/TryGhost/Team/issues/1869

- There are multiple places in the codebase fetching "default product". The code is slightly divergent in each one of them and has been a source of bugs (like the one referenced). Having the logic captured in one place will allow reducing the code duplication, making code less bug prone, and making testing the modules dependent on the "setDefaultProduct" method easier
This commit is contained in:
Naz 2022-10-20 14:56:57 +08:00
parent 02698b4559
commit 82ed10473b
No known key found for this signature in database
2 changed files with 43 additions and 0 deletions

View File

@ -128,6 +128,21 @@ class ProductRepository {
throw new NotFoundError({message: 'Missing id, slug, stripe_product_id or stripe_price_id from data'});
}
/**
* Fetches the default product
* @param {Object} options
* @returns {Promise<ProductModel>}
*/
async getDefaultProduct(options = {}) {
const defaultProductPage = await this.list({
filter: 'type:paid+active:true',
limit: 1,
...options
});
return defaultProductPage.data[0];
}
/**
* Creates a product from a name
*

View File

@ -0,0 +1,28 @@
const assert = require('assert');
const sinon = require('sinon');
const ProductRepository = require('../../../../lib/repositories/product');
describe('MemberRepository', function () {
describe('getDefaultProduct', function () {
it('calls list method with specific parameters', async function () {
const productRepository = new ProductRepository({});
const listStub = sinon.stub(productRepository, 'list').resolves({
data: [{
id: 'default_product_id'
}]
});
const defaultProduct = await productRepository.getDefaultProduct({
withRelated: ['stripePrices']
});
assert.ok(listStub.called);
assert.equal(listStub.args[0][0].filter, 'type:paid+active:true', 'should only take into account paid and active records');
assert.equal(listStub.args[0][0].limit, 1, 'should only fetch a single record');
assert.deepEqual(listStub.args[0][0].withRelated, ['stripePrices'], 'should extend passed in options');
assert.equal(defaultProduct.id, 'default_product_id', 'returns a single product object');
});
});
});