Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions src/utils/__tests__/validateFields.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -371,4 +371,53 @@ describe('test Utils/validateFields', () => {
)
);
});

it.each`
input | expectedOutcome
${1} | ${'valid'}
${'1'} | ${'invalid'}
${0} | ${'valid'}
${'0'} | ${'invalid'}
${true} | ${'valid'}
${'true'} | ${'valid'}
${false} | ${'valid'}
${'false'} | ${'valid'}
${'string-input'} | ${'invalid'}
${'2'} | ${'invalid'}
${3} | ${'invalid'}
`(
'should be able to validate boolean input and throws an error if invalid',
async ({ input, expectedOutcome }) => {
const testInput = {
booleanCheck: input,
};
const inputFields = [
{
key: 'booleanCheck',
type: 'boolean',
required: true,
},
];

try {
const validated = validateFields(testInput, inputFields);

if (expectedOutcome === 'valid') {
expect(validated).toEqual(testInput);
} else {
expect(validated).toThrow();
}
} catch (e) {
expect(e.name).toEqual('LesgoException');
expect(e.message).toEqual(
`Invalid type for 'booleanCheck', expecting 'boolean'`
);
expect(e.code).toEqual(`${FILE}::INVALID_TYPE_BOOLEANCHECK`);
expect(e.extra).toStrictEqual({
field: inputFields[0],
value: input,
});
}
}
);
});
13 changes: 12 additions & 1 deletion src/utils/validateFields.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,16 @@ const isValidJSON = json => {
}
};

const isValidBoolean = input => {
if (typeof input === 'string') {
return input === 'true' || input === 'false';
}
if (typeof input === 'number') {
return input === 1 || input === 0;
}
return typeof input === 'boolean';
};

const validateFields = (params, validFields) => {
const validated = {};

Expand All @@ -37,7 +47,7 @@ const validateFields = (params, validFields) => {
}
}

if (!params[key]) {
if (type !== 'boolean' && !params[key]) {
if (typeof params[key] !== 'number') {
throw new LesgoException(
`Missing required '${key}'`,
Expand Down Expand Up @@ -66,6 +76,7 @@ const validateFields = (params, validFields) => {

(isCollection ? params[key] || [] : [params[key]]).forEach(paramsItem => {
if (
(type === 'boolean' && !isValidBoolean(paramsItem)) ||
(type === 'string' &&
typeof paramsItem !== 'undefined' &&
typeof paramsItem !== 'string') ||
Expand Down