Discriminator support for examples (fixes #65)

This commit is contained in:
Roman Hotsiy 2016-07-15 17:43:01 +03:00
parent efa7811e74
commit dcd43e4fc6
No known key found for this signature in database
GPG Key ID: 5CB7B3ACABA57CB0
3 changed files with 21 additions and 3 deletions

View File

@ -43,7 +43,21 @@ export class SchemaSample extends BaseComponent {
if (base.examples && base.examples['application/json']) {
sample = base.examples['application/json'];
} else {
let selectedDescendant;
this.componentSchema = this._normalizer.normalize(this.componentSchema, this.pointer);
let discriminator = this.componentSchema.discriminator;
if (discriminator) {
let descendants = this.specMgr.findDerivedDefinitions(this.componentSchema._pointer || this.pointer);
if (descendants.length) {
// TODO: sync up with dropdown
selectedDescendant = descendants[0];
let descSchema = this.specMgr.byPointer(selectedDescendant.$ref);
this.componentSchema = this._normalizer.normalize(Object.assign({}, descSchema), selectedDescendant.$ref,
{omitParent: false});
}
}
if (this.fromCache()) {
return;
}
@ -54,6 +68,9 @@ export class SchemaSample extends BaseComponent {
} catch(e) {
// no sample available
}
if (selectedDescendant) {
sample[discriminator] = selectedDescendant.name;
}
}
this.cache(sample);
this.data.sample = sample;

View File

@ -22,13 +22,14 @@ export class SchemaNormalizer {
constructor(private _schema:any) {
this._dereferencer = new SchemaDereferencer(_schema, this);
}
normalize(schema, ptr) {
normalize(schema, ptr, opts:any ={}) {
opts.omitParent = opts.omitParent !== false;
if (schema['x-redoc-normalized']) return schema;
let res = SchemaWalker.walk(schema, ptr, (subSchema, ptr) => {
let resolved = this._dereferencer.dereference(subSchema, ptr);
if (resolved.allOf) {
resolved._pointer = resolved._pointer || ptr;
AllOfMerger.merge(resolved, resolved.allOf, {omitParent: true});
AllOfMerger.merge(resolved, resolved.allOf, {omitParent: opts.omitParent});
}
return resolved;
});

View File

@ -124,7 +124,7 @@ export class SpecManager {
if (!globalDefs[defName].allOf &&
!globalDefs[defName]['x-derived-from']) continue;
let subTypes = globalDefs[defName]['x-derived-from'] ||
globalDefs[defName].allOf.map(subType => subType.$ref);
globalDefs[defName].allOf.map(subType => subType._pointer || subType.$ref);
let idx = subTypes.findIndex(ref => ref === defPointer);
if (idx < 0) continue;