Skip to content

Commit

Permalink
Added 'getDefaultProduct' convenience method to product repo
Browse files Browse the repository at this point in the history
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
  • Loading branch information
naz committed Oct 20, 2022
1 parent 02698b4 commit 82ed104
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
15 changes: 15 additions & 0 deletions ghost/members-api/lib/repositories/product.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
*
Expand Down
28 changes: 28 additions & 0 deletions ghost/members-api/test/unit/lib/repositories/product.test.js
Original file line number Diff line number Diff line change
@@ -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');
});
});
});

0 comments on commit 82ed104

Please sign in to comment.