Merge pull request #543 from smartxworks/fix/default-value

fix(shared): use default value instead of  undefined when generate default value from spec
This commit is contained in:
tanbowensg 2022-07-26 11:07:02 +08:00 committed by GitHub
commit 382240f432
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 10 additions and 17 deletions

View File

@ -17,14 +17,9 @@ describe('generateDefaultValueFromSpec function', () => {
const type = Type.Number();
expect(generateDefaultValueFromSpec(type)).toEqual(0);
});
// Type.Optional can only be judged by the modifier feature provided by the typebox,
// but this would break the consistency of the function,
// and it doesn't seem to make much sense to deal with non-object optional alone like Type.Optional(Type.String())
// Therefore it is possible to determine whether an object's property is optional using spec.required,
// and if the property is within Type.Object is optional then it is not required.
it('can parse optional', () => {
it('can parse optional and the value is the default value of its type', () => {
const type = Type.Optional(Type.Object({ str: Type.Optional(Type.String()) }));
expect(generateDefaultValueFromSpec(type)).toEqual({ str: undefined });
expect(generateDefaultValueFromSpec(type)).toEqual({ str: '' });
});
it('can parse object', () => {
const type = Type.Object({

View File

@ -31,7 +31,6 @@ function getArray(items: JSONSchema7Definition[]): JSONSchema7Type[] {
function getObject(spec: JSONSchema7): JSONSchema7Object {
const obj: JSONSchema7Object = {};
const requiredKeys = spec.required;
if (spec.allOf && spec.allOf.length > 0) {
return (getArray(spec.allOf) as JSONSchema7Object[]).reduce((prev, cur) => {
@ -40,15 +39,14 @@ function getObject(spec: JSONSchema7): JSONSchema7Object {
}, obj);
}
requiredKeys &&
requiredKeys.forEach(key => {
const subSpec = spec.properties?.[key];
if (typeof subSpec === 'boolean') {
obj[key] = null;
} else if (subSpec) {
obj[key] = generateDefaultValueFromSpec(subSpec);
}
});
for (const key in spec.properties) {
const subSpec = spec.properties?.[key];
if (typeof subSpec === 'boolean') {
obj[key] = null;
} else if (subSpec) {
obj[key] = generateDefaultValueFromSpec(subSpec);
}
}
return obj;
}