Added custom formatter functionality to MaxLimit

refs https://linear.app/tryghost/issue/CORE-121/create-a-video-storage-adapter

 - Some variables (like file size) would be hard to comprehend with the default formatting. Instead allowed MaxLimit to be configured with a custom formatter
This commit is contained in:
Naz 2021-10-26 15:49:26 +04:00
parent 945e7ab520
commit 4172f993d4
2 changed files with 12 additions and 3 deletions

View File

@ -45,6 +45,7 @@ class MaxLimit extends Limit {
* @param {Object} options.config - limit configuration
* @param {Number} options.config.max - maximum limit the limit would check against
* @param {Function} options.config.currentCountQuery - query checking the state that would be compared against the limit
* @param {Function} [options.config.formatter] - function to format the limit counts before they are passed to the error message
* @param {String} [options.config.error] - error message to use when limit is reached
* @param {String} [options.helpLink] - URL to the resource explaining how the limit works
* @param {Object} [options.db] - instance of knex db connection that currentCountQuery can use to run state check through
@ -63,20 +64,27 @@ class MaxLimit extends Limit {
this.currentCountQueryFn = config.currentCountQuery;
this.max = config.max;
this.formatter = config.formatter;
this.fallbackMessage = `This action would exceed the ${_.lowerCase(this.name)} limit on your current plan.`;
}
/**
*
* @param {Number} count - current count that acceded the limit
* @returns {Object} instance of HostLimitError
*/
generateError(count) {
let errorObj = super.generateError();
errorObj.message = this.fallbackMessage;
if (this.error) {
const formatter = this.formatter || Intl.NumberFormat().format;
try {
errorObj.message = _.template(this.error)(
{
max: Intl.NumberFormat().format(this.max),
count: Intl.NumberFormat().format(count),
max: formatter(this.max),
count: formatter(count),
name: this.name
});
} catch (e) {

View File

@ -96,6 +96,7 @@ describe('Limit Service', function () {
const _5MB = 5000000;
const config = {
max: _5MB,
formatter: count => `${count / 1000000}MB`,
error: 'You have exceeded the maximum file size {{ max }}',
currentCountQuery: function () {
throw new Error('Should not be called');
@ -116,7 +117,7 @@ describe('Limit Service', function () {
error.errorDetails.name.should.equal('fileSize');
error.errorDetails.limit.should.equal(5000000);
error.errorDetails.total.should.equal(10000000);
error.message.should.equal('You have exceeded the maximum file size 5,000,000');
error.message.should.equal('You have exceeded the maximum file size 5MB');
}
});
});