Skip to content

Commit

Permalink
Improve examples generation
Browse files Browse the repository at this point in the history
- Generate "additionalProperties" examples. Support the vendor extension "x-additionalPropertiesName"
- Use the default value if provided
- Generate null instead of a (potentially) invalid string if the type is not found (same behavior here as redoc and others)
  • Loading branch information
j3rem1e committed Aug 14, 2023
1 parent 34d4d00 commit 3e4a20c
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions src/utils/schema-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -223,17 +223,20 @@ export function getSampleValueByType(schemaObj) {
}
if (schemaObj.$ref) {
// Indicates a Circular ref
return schemaObj.$ref;
return {};
}
if (schemaObj.const === false || schemaObj.const === 0 || schemaObj.const === null || schemaObj.const === '') {
return schemaObj.const;
}
if (schemaObj.const) {
return schemaObj.const;
}
if (schemaObj.default) {
return schemaObj.default;
}
const typeValue = Array.isArray(schemaObj.type) ? schemaObj.type[0] : schemaObj.type;
if (!typeValue) {
return '?';
return null;
}
if (typeValue.match(/^integer|^number/g)) {
const multipleOf = Number.isNaN(Number(schemaObj.multipleOf)) ? undefined : Number(schemaObj.multipleOf);
Expand Down Expand Up @@ -297,7 +300,7 @@ export function getSampleValueByType(schemaObj) {
}
}
// If type cannot be determined
return '?';
return null;
}

/*
Expand Down Expand Up @@ -590,6 +593,11 @@ export function schemaToSampleObj(schema, config = { }) {
}
obj = mergePropertyExamples(obj, propertyName, schemaToSampleObj(schema.properties[propertyName], config));
}
if (typeof schema.additionalProperties === 'object') {
const propertyName = schema.additionalProperties['x-additionalPropertiesName'] || 'property';
obj = mergePropertyExamples(obj, `${propertyName}1`, schemaToSampleObj(schema.additionalProperties, config));
obj = mergePropertyExamples(obj, `${propertyName}2`, schemaToSampleObj(schema.additionalProperties, config));
}
}
} else if (schema.type === 'array' || schema.items) {
if (schema.items || schema.example) {
Expand Down

0 comments on commit 3e4a20c

Please sign in to comment.