Skip to content

Commit

Permalink
#40: update error message for type
Browse files Browse the repository at this point in the history
  • Loading branch information
mohit-s96 committed Oct 11, 2023
1 parent 336cdca commit 6fa9efc
Showing 1 changed file with 45 additions and 9 deletions.
54 changes: 45 additions & 9 deletions lib/schema/validate.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,29 @@ const ajv = new Ajv({ allErrors: true, coerceTypes: false, strict: true });
addFormats(ajv);
ajvErrors(ajv);

function determineType(value) {
if (value === null) {
return 'null';
}

if (Array.isArray(value)) {
return 'array';
}

// Distinguishing between integers and other numbers is not strictly possible in JS as all numbers are floating point
// But we can use a simple workaround to make the distinction
if (typeof value === 'number') {
if (Number.isInteger(value)) {
return 'integer';
} else {
return 'decimal';
}
}

// Other types (boolean and string) are covered by 'typeof'
return typeof value;
}

const addPayloadError = (resource, fileName, message, payloadErrors) => {
resource = resource || '_INVALID_';
if (!payloadErrors[resource]) {
Expand Down Expand Up @@ -129,6 +152,28 @@ function validatePayload({ payloads = {}, schema, resourceNameFromArgs = '', ver
const validate = ajv.compile(schema);
const valid = validate(payload);
if (!valid) {
for (const error of validate.errors) {
if (error.keyword === 'type') {
const nestedPayloadProperties = error?.instancePath?.split('/')?.slice(1) || [];

let resolvedKeyword = error.keyword;
if (error.keyword === 'errorMessage') {
resolvedKeyword = error?.params?.errors?.[0]?.keyword || error.keyword;
}
// find corresponding value in the payload
let failedItemValue = nestedPayloadProperties.reduce((acc, curr) => {
if (!acc && payload[curr]) return payload[curr];
return acc[curr];
}, null);

if (failedItemValue?.['constructor'] === Object && resolvedKeyword === 'additionalProperties') {
failedItemValue = 'additionalProperties';
}
const schemaType = error?.params?.type;
const schemaTypeFormatted = Array.isArray(error?.params?.type) ? schemaType.join(' or ') : schemaType;
error.message = `MUST be ${schemaTypeFormatted} but found ${determineType(failedItemValue)}`;
}
}
generateErrorReport({
validate,
json: payload,
Expand Down Expand Up @@ -260,15 +305,6 @@ function generateErrorReport({
if (keyword === 'errorMessage') {
resolvedKeyword = params?.errors?.[0]?.keyword || keyword;
}
// find corresponding value in the payload
let failedItemValue = nestedPayloadProperties.reduce((acc, curr) => {
if (!acc && json[curr]) return json[curr];
return acc[curr];
}, null);

if (failedItemValue?.['constructor'] === Object && resolvedKeyword === 'additionalProperties') {
failedItemValue = 'additionalProperties';
}

if (!cache[resourceName]) {
cache[resourceName] = {};
Expand Down

0 comments on commit 6fa9efc

Please sign in to comment.