fix(core): fix defaulting object properties to empty {} (#7288)

This commit is contained in:
Jason Jean 2021-10-08 13:15:37 -04:00 committed by GitHub
parent 5ae45b63dd
commit 4c4826667e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 95 additions and 3 deletions

View File

@ -565,6 +565,85 @@ describe('params', () => {
expect(opts).toEqual({ a: [] });
});
it('should set the default object value', () => {
const opts = setDefaults(
{
a: {
key: 'value',
},
},
{
properties: {
a: {
type: 'object',
properties: {
key: {
type: 'string',
},
key2: {
type: 'string',
default: 'value2',
},
},
},
},
}
);
expect(opts).toEqual({ a: { key: 'value', key2: 'value2' } });
});
it('should not default object properties to {}', () => {
const opts = setDefaults(
{},
{
properties: {
a: {
type: 'object',
properties: {
key: {
type: 'string',
},
},
},
},
}
);
expect(opts).toEqual({});
});
it('should be able to set defaults for underlying properties', () => {
const opts = setDefaults(
{},
{
properties: {
a: {
type: 'object',
properties: {
minify: {
type: 'boolean',
default: true,
},
inlineCritical: {
type: 'boolean',
default: true,
},
},
additionalProperties: false,
},
},
}
);
expect(opts).toEqual({
a: {
minify: true,
inlineCritical: true,
},
});
});
it('should resolve types using refs', () => {
const opts = setDefaults(
{},

View File

@ -16,7 +16,12 @@ type PropertyDescription = {
description?: string;
format?: string;
visible?: boolean;
default?: string | number | boolean | string[];
default?:
| string
| number
| boolean
| string[]
| { [key: string]: string | number | boolean | string[] };
$ref?: string;
$default?: { $source: 'argv'; index: number } | { $source: 'projectName' };
additionalProperties?: boolean;
@ -436,10 +441,18 @@ function setPropertyDefault(
opts[propName] = schema.default;
}
} else {
if (!opts[propName]) {
const wasUndefined = opts[propName] === undefined;
if (wasUndefined) {
// We need an object to set values onto
opts[propName] = {};
}
setDefaultsInObject(opts[propName], schema.properties || {}, definitions);
// If the property was initially undefined but no properties were added, we remove it again instead of having an {}
if (wasUndefined && Object.keys(opts[propName]).length === 0) {
delete opts[propName];
}
}
}

View File

@ -55,7 +55,7 @@ export function isWorkspaceProject(project: ProjectGraphNode) {
export function isNpmProject(
project: ProjectGraphNode
): project is ProjectGraphNode<{ packageName: string; version: string }> {
return project.type === 'npm';
return project?.type === 'npm';
}
export function getSortedProjectNodes(nodes: Record<string, ProjectGraphNode>) {