Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: handle allOf correctly for inheritance cases of problem JSON #52

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion functions/is-problem-json-schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,33 @@ const assertProblemSchema = (schema) => {
}
};

/*
* Merge list of schema definitions of type = 'object'.
* Return object will have a super set of attributes 'properties' and 'required'.
*/
const mergeObjectDefinitions = (allOfTypes) => {
if (allOfTypes.filter((item) => item.type !== 'object').length !== 0) {
throw "All schema definitions must be of type 'object'";
}

return allOfTypes.reduce((acc, item) => {
return {
type: 'object',
properties: { ...(acc.properties || {}), ...(item.properties || {}) },
required: [...(acc.required || []), ...(item.required || [])],
};
}, {});
};

const check = (schema) => {
const combinedSchemas = [...(schema.anyOf || []), ...(schema.oneOf || []), ...(schema.allOf || [])];
const combinedSchemas = [...(schema.anyOf || []), ...(schema.oneOf || [])];
if (schema.allOf) {
const mergedAllOf = mergeObjectDefinitions(schema.allOf);
if (mergedAllOf) {
combinedSchemas.push(mergedAllOf);
}
}

if (combinedSchemas.length > 0) {
combinedSchemas.forEach(check);
} else {
Expand Down
32 changes: 32 additions & 0 deletions tests/176-MUST-support-problem-JSON.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,36 @@ describe('MUST support problem JSON [176]', () => {
}),
]);
});

test('Verify custom problem extending valid problem object does not cause error', async () => {
const openApi = await loadOpenApiSpec('base-openapi.yml');

// define custom problem extending problem json
openApi.components.schemas['CustomValidationProblem'] = {
allOf: [
{ $ref: '#/components/schemas/Problem' },
{
type: 'object',
required: ['title', 'status', 'detail', 'validation_error'],
properties: {
validation_error: { type: 'string' },
},
},
],
};

openApi.paths['/example'].get.responses['400'] = {
description: 'bad request',
content: {
'application/problem+json': {
schema: {
$ref: '#/components/schemas/CustomValidationProblem',
},
},
},
};

const result = await lint(openApi);
expect(result).toEqual([]);
});
});
Loading