Last active
January 10, 2024 13:16
-
-
Save ikenna/0a2bb83d3cdca8614d29080225ae67d1 to your computer and use it in GitHub Desktop.
Redocly Linting rule to ensure that each operation has only one 2xx response.' (Generated from HuggingChat)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { RuleTester } = require('eslint'); | |
const openApiParser = require('openapi-parser'); | |
// Define the linting rule | |
const rule = { | |
meta: { | |
docs: { | |
description: 'Ensure an API operation has at most one 2xx response', | |
category: 'Best Practices', | |
recommended: true, | |
}, | |
schema: [], // No additional configuration needed for this rule | |
type: 'problem', // This is a problem/error reporting rule | |
}, | |
create: (context) => ({ | |
PathItemObject: (node) => { | |
const pathResponses = node?.responses || {}; | |
let twoXXCount = 0; | |
Object.entries(pathResponses).forEach(([code, response]) => { | |
if (+code >= 200 && +code <= 299) { | |
twoXXCount++; | |
if (twoXXCount > 1) { | |
context.report({ | |
node, | |
message: `Path "${node.key}" must not contain more than one 2xx status code response. Found ${code}.`, | |
}); | |
} | |
} | |
}); | |
}, | |
}), | |
}; | |
// Set up the RuleTester | |
const rtl = new RuleTester({ | |
parserOptions: { ecmaVersion: 6, sourceType: 'module' }, | |
}); | |
rtl.run('only_one_2xx_response', rule, { | |
valid: [{ filename: 'valid.yaml', code: '' }], | |
invalid: [ | |
{ | |
filename: 'invalid.yaml', | |
code: ` | |
openapi: "3.0.0" | |
paths: | |
/example: | |
get: | |
responses: | |
200: {} | |
201: {} | |
`, | |
}, | |
], | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
File to test with: