Fixed handling objects as API input parameters

fix https://linear.app/tryghost/issue/SLO-155/paramsmap-is-not-a-function-an-unexpected-error-occurred-please-try

- in the case you provide an object to the API, this code will throw an
  error because it can't map over an object
- we can just assert that params should be an array and throw an error
  otherwise
This commit is contained in:
Daniel Lockyer 2024-06-24 10:01:36 +02:00 committed by Daniel Lockyer
parent c1df0c9d3d
commit d5013199b3
2 changed files with 17 additions and 0 deletions

View File

@ -1,4 +1,5 @@
const _ = require('lodash');
const {IncorrectUsageError} = require('@tryghost/errors');
/**
* @description Helper function to prepare params for internal usages.
@ -15,6 +16,14 @@ const trimAndLowerCase = (params) => {
params = params.split(',');
}
// If we don't have an array at this point, something is wrong, so we should throw an
// error to avoid trying to .map over something else
if (!_.isArray(params)) {
throw new IncorrectUsageError({
message: 'Params must be a string or array'
});
}
return params.map((item) => {
return item.trim().toLowerCase();
});

View File

@ -20,4 +20,12 @@ describe('util/options', function () {
it('accepts parameters in form of an array', function () {
optionsUtil.trimAndLowerCase([' PeanUt', ' buTTer ']).should.eql(['peanut', 'butter']);
});
it('throws error for invalid object input', function () {
try {
optionsUtil.trimAndLowerCase({name: 'peanut'});
} catch (err) {
err.message.should.eql('Params must be a string or array');
}
});
});