Skip to content

Commit d212620

Browse files
alan-agius4Keen Yee Liau
authored and
Keen Yee Liau
committed
fix(@angular-devkit/core): add schema defaults when value is undefined
Related to #15207 (comment)
1 parent 1acfaae commit d212620

File tree

2 files changed

+39
-5
lines changed

2 files changed

+39
-5
lines changed

packages/angular_devkit/core/src/json/schema/registry_spec.ts

+36
Original file line numberDiff line numberDiff line change
@@ -445,4 +445,40 @@ describe('CoreSchemaRegistry', () => {
445445
.toPromise().then(done, done.fail);
446446
});
447447

448+
it('adds defaults to undefined properties', done => {
449+
const registry = new CoreSchemaRegistry();
450+
registry.addPostTransform(addUndefinedDefaults);
451+
// tslint:disable-line:no-any
452+
const data: any = {
453+
bool: undefined,
454+
str: undefined,
455+
obj: {
456+
num: undefined,
457+
},
458+
};
459+
460+
registry
461+
.compile({
462+
properties: {
463+
bool: { type: 'boolean', default: true },
464+
str: { type: 'string', default: 'someString' },
465+
obj: {
466+
properties: {
467+
num: { type: 'number', default: 0 },
468+
},
469+
},
470+
},
471+
})
472+
.pipe(
473+
mergeMap(validator => validator(data)),
474+
map(result => {
475+
expect(result.success).toBe(true);
476+
expect(data.bool).toBe(true);
477+
expect(data.str).toBe('someString');
478+
expect(data.obj.num).toBe(0);
479+
}),
480+
)
481+
.toPromise().then(done, done.fail);
482+
});
483+
448484
});

packages/angular_devkit/core/src/json/schema/transforms.ts

+3-5
Original file line numberDiff line numberDiff line change
@@ -63,15 +63,13 @@ export function addUndefinedDefaults(
6363
return newValue;
6464
}
6565

66-
for (const propName of Object.getOwnPropertyNames(schema.properties)) {
67-
if (propName in newValue) {
68-
continue;
69-
} else if (propName == '$schema') {
66+
for (const [propName, schemaObject] of Object.entries(schema.properties)) {
67+
if (newValue[propName] !== undefined || propName === '$schema') {
7068
continue;
7169
}
7270

7371
// TODO: Does not currently handle more complex schemas (oneOf/anyOf/etc.)
74-
const defaultValue = (schema.properties[propName] as JsonObject).default;
72+
const defaultValue = (schemaObject as JsonObject).default;
7573

7674
newValue[propName] = defaultValue;
7775
}

0 commit comments

Comments
 (0)