Skip to content

Commit

Permalink
feat: add support function to get all CommonModel dependencies (#105)
Browse files Browse the repository at this point in the history
  • Loading branch information
jonaslagoni authored Feb 24, 2021
1 parent 026bf0c commit 635e2e5
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 2 deletions.
36 changes: 34 additions & 2 deletions src/models/CommonModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import { Schema } from './Schema';
* @extends CommonSchema<CommonModel>
*/
export class CommonModel extends CommonSchema<CommonModel> {
extend?: string[]
originalSchema?: Schema | boolean
extend?: string[];
originalSchema?: Schema | boolean;

/**
* Transform object into a type of CommonModel.
Expand Down Expand Up @@ -169,4 +169,36 @@ export class CommonModel extends CommonSchema<CommonModel> {
}
return this.required.includes(propertyName);
}

/**
* This function returns an array of `$id`s from all the CommonModel's it immediate depends on.
*/
getImmediateDependencies(): string[] {
const dependsOn = [];
if (this.additionalProperties instanceof CommonModel) {
const additionalPropertiesRef = (this.additionalProperties as CommonModel).$ref;
if (additionalPropertiesRef !== undefined) {
dependsOn.push(additionalPropertiesRef);
}
}
if (this.extend !== undefined) {
for (const extendedSchema of this.extend) {
dependsOn.push(extendedSchema);
}
}
if (this.items instanceof CommonModel) {
const itemsRef = (this.items as CommonModel).$ref;
if (itemsRef !== undefined) {
dependsOn.push(itemsRef);
}
}
if (this.properties !== undefined && Object.keys(this.properties).length) {
Object.entries(this.properties).forEach(([, propertyModel]) => {
if (propertyModel.$ref !== undefined) {
dependsOn.push(propertyModel.$ref);
}
});
}
return dependsOn;
}
}
13 changes: 13 additions & 0 deletions test/models/CommonModel.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -393,5 +393,18 @@ describe('CommonModel', function() {
expect(d.isRequired("propX")).toEqual(false);
});
});

describe('getImmediateDependencies', function() {
test('check that all dependencies are returned', function() {
const doc = { additionalProperties: { $ref: "1" }, extend: ["2"], items: { $ref: "3" }, properties: { testProp: { $ref: "4" } } };
const d = CommonModel.toCommonModel(doc);
expect(d.getImmediateDependencies()).toEqual(["1", "2", "3", "4"]);
});
test('check that no dependencies is returned if there are none', function() {
const doc = { };
const d = CommonModel.toCommonModel(doc);
expect(d.getImmediateDependencies()).toEqual([]);
});
});
});
});

0 comments on commit 635e2e5

Please sign in to comment.