Skip to content

Instantly share code, notes, and snippets.

@ikenna
Last active January 10, 2024 13:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ikenna/0a2bb83d3cdca8614d29080225ae67d1 to your computer and use it in GitHub Desktop.
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)
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: {}
`,
},
],
});
@ikenna
Copy link
Author

ikenna commented Jan 10, 2024

File to test with:

openapi: 3.0.0
info:
  title: Test API
  version: 1.0.0
servers:
  - url: https://test.com/api
paths:
  /example:
    get:
      summary: Example GET request
      description: An example endpoint with multiple 2xx responses
      responses:
        200:
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ExampleResponse'
        201:
          description: Created resource
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreatedResource'
components:
  schemas:
    ExampleResponse:
      type: object
      properties:
        id:
          type: string
          example: abcdefg
    CreatedResource:
      type: object
      properties:
        createdAt:
          type: string
          format: date-time
          example: 2022-05-04T18:17:41Z

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment