Skip to content

Commit

Permalink
feat: format object properties with types
Browse files Browse the repository at this point in the history
  • Loading branch information
vankop committed Sep 28, 2019
1 parent 338db8b commit cea95fb
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 43 deletions.
28 changes: 21 additions & 7 deletions src/ValidationError.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,25 @@ const SPECIFICITY = {
absolutePath: 2,
};

function createPropertyFormatter(schema) {
const required = new Set(schema.required || []);
const format = (property) => property + (required.has(property) ? '' : '?');

return function formatProperty(property) {
const { type } =
typeof schema.properties === 'object' && schema.properties !== null
? schema.properties[property] || {}
: {};
const name = format(property);

if (type) {
return `${name}: ${type}`;
}

return name;
};
}

function filterMax(array, fn) {
const evaluatedMax = array.reduce((max, item) => Math.max(max, fn(item)), 0);

Expand Down Expand Up @@ -530,6 +549,7 @@ class ValidationError extends Error {
);
}

const formatter = createPropertyFormatter(schema);
const properties = schema.properties
? Object.keys(schema.properties)
: [];
Expand All @@ -542,13 +562,7 @@ class ValidationError extends Error {
Boolean(schema.additionalProperties);

const objectStructure = allProperties
.map((property) => {
const isRequired = required.includes(property);

// Some properties need quotes, maybe we should add check
// Maybe we should output type of property (`foo: string`), but it is looks very unreadable
return `${property}${isRequired ? '' : '?'}`;
})
.map(formatter)
.concat(
hasAdditionalProperties
? isObject(schema.additionalProperties)
Expand Down
Loading

0 comments on commit cea95fb

Please sign in to comment.