fix(@angular-devkit/core): add schema defaults when value is undefined

Related to https://github.com/angular/angular-cli/pull/15207#discussion_r309175463
This commit is contained in:
Alan Agius 2019-08-01 13:44:10 +02:00 committed by Keen Yee Liau
parent 195e493a66
commit 6f0e7bf437
2 changed files with 39 additions and 5 deletions

View File

@ -445,4 +445,40 @@ describe('CoreSchemaRegistry', () => {
.toPromise().then(done, done.fail);
});
it('adds defaults to undefined properties', done => {
const registry = new CoreSchemaRegistry();
registry.addPostTransform(addUndefinedDefaults);
// tslint:disable-line:no-any
const data: any = {
bool: undefined,
str: undefined,
obj: {
num: undefined,
},
};
registry
.compile({
properties: {
bool: { type: 'boolean', default: true },
str: { type: 'string', default: 'someString' },
obj: {
properties: {
num: { type: 'number', default: 0 },
},
},
},
})
.pipe(
mergeMap(validator => validator(data)),
map(result => {
expect(result.success).toBe(true);
expect(data.bool).toBe(true);
expect(data.str).toBe('someString');
expect(data.obj.num).toBe(0);
}),
)
.toPromise().then(done, done.fail);
});
});

View File

@ -63,15 +63,13 @@ export function addUndefinedDefaults(
return newValue;
}
for (const propName of Object.getOwnPropertyNames(schema.properties)) {
if (propName in newValue) {
continue;
} else if (propName == '$schema') {
for (const [propName, schemaObject] of Object.entries(schema.properties)) {
if (newValue[propName] !== undefined || propName === '$schema') {
continue;
}
// TODO: Does not currently handle more complex schemas (oneOf/anyOf/etc.)
const defaultValue = (schema.properties[propName] as JsonObject).default;
const defaultValue = (schemaObject as JsonObject).default;
newValue[propName] = defaultValue;
}