Skip to content

rewrite if/then/else as oneOf: [allOf: [X, Y], allOf: [not: X, Z]] #15

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

Merged
merged 2 commits into from
Dec 18, 2018
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
24 changes: 24 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ function convertSchema(schema, path, parent, parentPath) {
schema = stripIllegalKeywords(schema);
schema = convertTypes(schema);
schema = convertDependencies(schema);
schema = rewriteIfThenElse(schema);
schema = rewriteExclusiveMinMax(schema);

if (typeof schema['patternProperties'] === 'object') {
Expand Down Expand Up @@ -145,6 +146,28 @@ function convertPatternProperties(schema) {
return schema;
}

function rewriteIfThenElse(schema) {
/* @handrews https://github.com/OAI/OpenAPI-Specification/pull/1766#issuecomment-442652805
if and the *Of keywords

There is a really easy solution for implementations, which is that

if: X, then: Y, else: Z

is equivalent to

oneOf: [allOf: [X, Y], allOf: [not: X, Z]]
*/
if (schema.if && schema.then) {
schema.oneOf = [ { allOf: [ schema.if, schema.then ] },
{ allOf: [ { not: schema.if }, schema.else ] } ];
delete schema.if;
delete schema.then;
delete schema.else;
}
return schema;
}

function rewriteExclusiveMinMax(schema) {
if (typeof schema.exclusiveMaximum === 'number') {
schema.maximum = schema.exclusiveMaximum;
Expand All @@ -158,3 +181,4 @@ function rewriteExclusiveMinMax(schema) {
}

module.exports = convert;

24 changes: 24 additions & 0 deletions test/if-then-else.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
'use strict';

const convert = require('../');
const should = require('should');

it('if-then-else', () => {
const schema = {
$schema: 'http://json-schema.org/draft-04/schema#',
if: { type: 'object' },
then: { properties: { id: { type: 'string' } } },
else: { format: 'uuid' }
};

const result = convert(schema);

const expected = {
oneOf: [
{ allOf: [ { type: 'object' }, { properties: { id: { type: 'string' } } } ] },
{ allOf: [ { not: { type: 'object' } }, { format: 'uuid' } ] }
]
};

should(result).deepEqual(expected, 'converted');
});