diff --git a/packages/shared/__tests__/spec.spec.ts b/packages/shared/__tests__/spec.spec.ts index 16c56e67..0efaacc3 100644 --- a/packages/shared/__tests__/spec.spec.ts +++ b/packages/shared/__tests__/spec.spec.ts @@ -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({ diff --git a/packages/shared/src/utils/spec.ts b/packages/shared/src/utils/spec.ts index ef496aa1..84865571 100644 --- a/packages/shared/src/utils/spec.ts +++ b/packages/shared/src/utils/spec.ts @@ -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; }