Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: format object properties with types #59

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
28 changes: 21 additions & 7 deletions src/ValidationError.js
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