Skip to content

Commit

Permalink
fix: sort discriminator entries by mapping order (#1216)
Browse files Browse the repository at this point in the history
* sort discriminator entries by mapping order

* fix string compare
  • Loading branch information
zeapo authored Mar 27, 2020
1 parent ea5b0aa commit ac4f915
Showing 1 changed file with 30 additions and 1 deletion.
31 changes: 30 additions & 1 deletion src/services/models/Schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ export class SchemaModel {

const inversedMapping = isLimitedToMapping ? { ...explicitInversedMapping } : { ...implicitInversedMapping, ...explicitInversedMapping };

const refs: Array<{ $ref; name }> = [];
let refs: Array<{ $ref; name }> = [];

for (const $ref of Object.keys(inversedMapping)) {
const names = inversedMapping[$ref];
Expand All @@ -276,6 +276,35 @@ export class SchemaModel {
}
}

// Make the listing respects the mapping
// in case a mapping is defined, the user usually wants to have the order shown
// as it was defined in the yaml. This will sort the names given the provided
// mapping (if provided).
// The logic is:
// - If a name is among the mapping, promote it to first
// - Names among the mapping are sorted by their order in the mapping
// - Names outside the mapping are sorted alphabetically
const names = Object.keys(mapping);
if (names.length !== 0) {
refs = refs.sort((left, right) => {
const indexLeft = names.indexOf(left.name);
const indexRight = names.indexOf(right.name);

if (indexLeft < 0 && indexRight < 0) {
// out of mapping, order by name
return left.name.localCompare(right.name);
} else if (indexLeft < 0) {
// the right is found, so mapping wins
return 1;
} else if (indexRight < 0) {
// left wins as it's in mapping
return -1;
} else {
return indexLeft - indexRight;
}
});
}

this.oneOf = refs.map(({ $ref, name }) => {
const innerSchema = new SchemaModel(parser, parser.byRef($ref)!, $ref, this.options, true);
innerSchema.title = name;
Expand Down

0 comments on commit ac4f915

Please sign in to comment.