Correctly parse config string values from int array

This commit is contained in:
timvisee 2021-05-19 11:48:20 +02:00
parent 1d6872e279
commit 20cf722b54
No known key found for this signature in database
GPG Key ID: B8DB720BC383E172
1 changed files with 13 additions and 10 deletions

View File

@ -5,19 +5,22 @@ const { randomBytes } = require('crypto');
convict.addFormat({ convict.addFormat({
name: 'positive-int-array', name: 'positive-int-array',
coerce: (ints, schema) => { // can take: int[] | string[] | string (csv), returns -> int[] coerce: ints => {
const ints_arr = Array.isArray(ints) ? ints : ints.trim().split(',') // can take: int[] | string[] | string (csv), returns -> int[]
return ints_arr.map(int => const ints_arr = Array.isArray(ints) ? ints : ints.trim().split(',');
(typeof int === 'number') return ints_arr.map(int =>
? int typeof int === 'number'
: parseInt(int.trim(), 10)) ? int
: parseInt(int.replace(/['"]+/g, '').trim(), 10)
);
}, },
validate: (ints, schema) => { // takes: int[], errors if any NaNs, negatives, or floats present validate: ints => {
// takes: int[], errors if any NaNs, negatives, or floats present
for (const int of ints) { for (const int of ints) {
if (typeof(int) !== 'number' || isNaN(int) || int < 0 || int % 1 > 0) if (typeof int !== 'number' || isNaN(int) || int < 0 || int % 1 > 0)
throw new Error('must be a comma-separated list of positive integers') throw new Error('must be a comma-separated list of positive integers');
} }
}, }
}); });
const conf = convict({ const conf = convict({