Skip to content

Commit

Permalink
Added a linter for order of parameters.
Browse files Browse the repository at this point in the history
Signed-off-by: dblock <[email protected]>
  • Loading branch information
dblock committed Jun 28, 2024
1 parent ed3fb4d commit 876e1d2
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
12 changes: 12 additions & 0 deletions tools/src/linter/components/Operation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export default class Operation extends ValidatorBase {
this.validate_request_body(),
this.validate_parameters(),
this.validate_path_parameters(),
this.validate_order_of_parameters(),
...this.validate_responses()
].filter((e) => e) as ValidationError[]
}
Expand Down Expand Up @@ -99,6 +100,17 @@ export default class Operation extends ValidatorBase {
}
}

validate_order_of_parameters(): ValidationError | undefined {
const parameters = this.spec.parameters
const unsorted_refs = _.map(parameters, (parameter) => parameter.$ref)
const sorted_refs = _.sortBy(_.map(parameters, (parameter) => parameter.$ref))
if (!_.isEqual(sorted_refs, unsorted_refs)) {
return this.error(
`Parameters in ${this.path} must be sorted. Expected ${_.join(sorted_refs, ', ')}.`,
this.path)
}
}

validate_path_parameters (): ValidationError | undefined {
const path_params = this.path_params()
const expected = this.path.match(/{[a-z0-9_]+}/g)?.map(p => p.slice(1, -1)) ?? []
Expand Down
26 changes: 26 additions & 0 deletions tools/tests/linter/Operation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,32 @@ test('validate_parameters()', () => {
.toEqual(invalid_parameters.error('Every parameter must be a reference object to \'#/components/parameters/{x-operation-group}::{path|query}.{parameter_name}\'.'))
})

test('validate_order_of_parameters()', () => {
const valid_parameters = operation({
parameters: [
{ $ref: 'path.index' },
{ $ref: 'query:pretty' },
{ $ref: 'timeout' }
]
})
expect(valid_parameters.validate_order_of_parameters())
.toBeUndefined()

const invalid_parameters = operation({
parameters: [
{ $ref: 'query:pretty' },
{ $ref: 'path.index' },
{ $ref: 'timeout' }
]
})
expect(invalid_parameters.validate_order_of_parameters())
.toEqual({
"file": "namespaces/indices.yaml",
"location": "/{index}/something/{abc_xyz}",
"message": "Parameters in /{index}/something/{abc_xyz} must be sorted. Expected path.index, query:pretty, timeout."
})
})

test('validate_path_parameters()', () => {
const invalid_path_params = operation({ parameters: [{ $ref: '#/components/parameters/indices.create::path.index' }] })
expect(invalid_path_params.validate_path_parameters())
Expand Down

0 comments on commit 876e1d2

Please sign in to comment.