Implemented findDerivedDefs routine

This commit is contained in:
Roman Hotsiy 2016-01-09 16:52:24 +02:00
parent 1d493f3ea5
commit ba2571a446
3 changed files with 77 additions and 1 deletions

View File

@ -156,4 +156,27 @@ export default class SchemaManager {
return tag2MethodMapping;
}
findDerivedDefinitions(defPointer) {
let definition = this.byPointer(defPointer);
// FIXME maybe not throw?
if (!definition.discriminator) return [];
let globalDefs = this._schema.definitions || {};
let res = [];
for (let defName of Object.keys(globalDefs)) {
if (!globalDefs[defName].allOf) continue;
let subTypes = globalDefs[defName].allOf;
let idx = subTypes.findIndex((subType) => {
if (subType.$ref === defPointer) return true;
return false;
});
if (idx < 0) continue;
res.push(defName);
}
return res;
}
}

View File

@ -772,8 +772,12 @@
},
"Pet": {
"type": "object",
"required": ["name", "photoUrls"],
"required": ["name", "photoUrls", "petType"],
"discriminator": "petType",
"properties": {
"petType": {
"type": "string"
},
"id": {
"type": "integer",
"format": "int64"
@ -815,6 +819,33 @@
"name": "Pet"
}
},
"Cat": {
"description": "A representation of a cat",
"allOf": [
{
"type": "object",
"properties": {
"huntingSkill": {
"type": "string",
"description": "The measured skill for hunting",
"default": "lazy",
"enum": [
"clueless",
"lazy",
"adventurous",
"aggressive"
]
}
},
"required": [
"huntingSkill"
]
},
{
"$ref": "#/definitions/Pet"
},
]
},
"ApiResponse": {
"type": "object",
"properties": {

View File

@ -225,5 +225,27 @@ describe('Utils', () => {
});
});
describe('findDerivedDefinitions method', () => {
beforeAll((done) => {
schemaMgr.load('/tests/schemas/extended-petstore.json').then(() => {
done();
}, () => {
done(new Error('Error handler should not be called'));
});
});
it('should find derived definitions for Pet', () => {
let deriveDefs = schemaMgr.findDerivedDefinitions('#/definitions/Pet');
deriveDefs.should.be.instanceof(Array);
deriveDefs.should.not.be.empty;
deriveDefs.should.be.deepEqual(['Cat']);
});
it('should return emtpy array for definitions that dont have discriminator', () => {
let deriveDefs = schemaMgr.findDerivedDefinitions('#/definitions/Order');
deriveDefs.should.be.instanceof(Array);
deriveDefs.should.be.empty;
});
});
});
});