diff --git a/.spectral.yml b/.spectral.yml index d13bc69..c12cf62 100644 --- a/.spectral.yml +++ b/.spectral.yml @@ -7,6 +7,7 @@ extends: [spectral:oas] functions: - requireExampleOrRef + - requireRequestBodyDescription rules: # ============================================================================= @@ -94,13 +95,12 @@ rules: function: requireExampleOrRef entur-request-body-description: - message: "Request bodies SHOULD have a description." + message: "Request bodies SHOULD have a description, either directly or on the referenced schema." documentationUrl: "https://github.com/entur/api-guidelines/blob/main/guidelines.md#21-general-design-principles" severity: warn given: $.paths.*.*.requestBody then: - field: description - function: truthy + function: requireRequestBodyDescription entur-response-body-examples: message: "Response bodies SHOULD include at least one example." diff --git a/functions/requireRequestBodyDescription.js b/functions/requireRequestBodyDescription.js new file mode 100644 index 0000000..c2b2864 --- /dev/null +++ b/functions/requireRequestBodyDescription.js @@ -0,0 +1,38 @@ +/** + * Custom Spectral function to check if a request body has a description, + * either directly on the requestBody or on the resolved schema reference. + */ +module.exports = (targetVal) => { + // Check if there's a direct description on the requestBody + if (targetVal.description) { + return; + } + + // Check if the resolved schema has a description + if (targetVal.content) { + for (const [mediaTypeName, mediaType] of Object.entries(targetVal.content)) { + if (!mediaType.schema) { + return [{ message: `Request body SHOULD have a description, either directly or on the referenced schema. Media type "${mediaTypeName}" has no schema.` }]; + } + + const schema = mediaType.schema; + + // Direct description on schema + if (schema.description) { + continue; + } + + // Array schema with items that have a description + if (schema.type === 'array' && schema.items && schema.items.description) { + continue; + } + + return [{ message: `Request body SHOULD have a description, either directly or on the referenced schema. Media type "${mediaTypeName}" is missing a description.` }]; + } + + // All media types have descriptions + return; + } + + return [{ message: 'Request body SHOULD have a description, either directly or on the referenced schema.' }]; +}; \ No newline at end of file