From 73e73194067c64f7f6047a91b2aa369a33839525 Mon Sep 17 00:00:00 2001 From: Naz Date: Thu, 1 Apr 2021 17:59:52 +1300 Subject: [PATCH] Added optional max limit override to errorIfWouldGoOverLimit refs https://github.com/TryGhost/Team/issues/587 - The optional {max} passed as an option allows to override currently configured limit and do a theoretical new limit check. For example: check if the max limit will be exceeded if the limit changes (user changes plans) --- ghost/limit-service/lib/limit.js | 12 +++++++++-- ghost/limit-service/test/limit.test.js | 29 ++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/ghost/limit-service/lib/limit.js b/ghost/limit-service/lib/limit.js index ca2f7a1cf8..4731d61f17 100644 --- a/ghost/limit-service/lib/limit.js +++ b/ghost/limit-service/lib/limit.js @@ -81,12 +81,20 @@ class MaxLimit extends Limit { return await this.currentCountQueryFn(this.db); } - async errorIfWouldGoOverLimit() { + /** + * Throws a HostLimitError if the configured or passed max limit is ecceded by currentCountQuery + * + * @param {Object} options + * @param {Number} [options.max] - overrides configured default max value to perform checks against + */ + async errorIfWouldGoOverLimit({max} = {}) { let currentCount = await this.currentCountQuery(this.db); - if ((currentCount + 1) > this.max) { + + if ((currentCount + 1) > (max || this.max)) { throw this.generateError(currentCount); } } + async errorIfIsOverLimit() { let currentCount = await this.currentCountQuery(this.db); if (currentCount > this.max) { diff --git a/ghost/limit-service/test/limit.test.js b/ghost/limit-service/test/limit.test.js index 3e771cf363..fc57babddd 100644 --- a/ghost/limit-service/test/limit.test.js +++ b/ghost/limit-service/test/limit.test.js @@ -66,5 +66,34 @@ describe('Limit Service', function () { await limit.errorIfWouldGoOverLimit(); }); + + it('ignores default configured max limit when it is passed explicitly', async function () { + const config = { + max: 10, + currentCountQuery: () => 10 + }; + + const limit = new MaxLimit({name: 'maxy', config}); + + // should pass as the limit is overridden to 10 + 1 = 11 + await limit.errorIfWouldGoOverLimit({max: 11}); + + try { + // should fail because limit is overridden to 10 + 1 < 1 + await limit.errorIfWouldGoOverLimit({max: 1}); + should.fail(limit, 'Should have errored'); + } catch (err) { + should.exist(err); + + should.exist(err.errorType); + should.equal(err.errorType, 'HostLimitError'); + + should.exist(err.errorDetails); + should.equal(err.errorDetails.name, 'maxy'); + + should.exist(err.message); + should.equal(err.message, 'This action would exceed the maxy limit on your current plan.'); + } + }); }); });