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

fixes createDefaultValue doesn't follow anyOf, oneOf, allOf #2401 #2402

Merged
merged 7 commits into from
Dec 6, 2024
67 changes: 62 additions & 5 deletions packages/core/src/mappers/renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,9 +168,13 @@ export const showAsRequired = (
*/
export const createDefaultValue = (
schema: JsonSchema,
rootSchema: JsonSchema
) => {
const resolvedSchema = Resolve.schema(schema, schema.$ref, rootSchema);
rootSchema: JsonSchema,
defaultValue: any = {}
): any => {
const resolvedSchema =
typeof schema.$ref === 'string'
? Resolve.schema(rootSchema, schema.$ref, rootSchema)
: schema;
if (resolvedSchema.default !== undefined) {
return extractDefaults(resolvedSchema, rootSchema);
}
Expand All @@ -196,9 +200,62 @@ export const createDefaultValue = (
return extractDefaults(resolvedSchema, rootSchema);
} else if (hasType(resolvedSchema, 'null')) {
return null;
} else {
return {};
}

let combinatorDefault = undefined;

combinatorDefault = createDefaultValueForCombinatorSchema(
kchobantonov marked this conversation as resolved.
Show resolved Hide resolved
schema.oneOf,
rootSchema
);
if (combinatorDefault !== undefined) {
return combinatorDefault;
}

combinatorDefault = createDefaultValueForCombinatorSchema(
schema.anyOf,
rootSchema
);
if (combinatorDefault !== undefined) {
return combinatorDefault;
}

combinatorDefault = createDefaultValueForCombinatorSchema(
schema.allOf,
rootSchema
);
if (combinatorDefault !== undefined) {
return combinatorDefault;
}

return defaultValue;
};

const createDefaultValueForCombinatorSchema = (
combinatorSchema: JsonSchema[],
rootSchema: JsonSchema
) => {
if (
combinatorSchema &&
Array.isArray(combinatorSchema) &&
combinatorSchema.length > 0
) {
const noDefaultValue = Symbol.for('noDefaultValue');
for (const combineSchema of combinatorSchema) {
const result = createDefaultValue(
combineSchema,
rootSchema,
noDefaultValue
);
if (result !== noDefaultValue) {
// return the first one that have type information
return result;
}
}
}

// no default value found
return undefined;
};

/**
Expand Down