Skip to content

Commit

Permalink
Merge pull request #15 from MikeRalphson/if-then-else
Browse files Browse the repository at this point in the history
rewrite if/then/else as oneOf: [allOf: [X, Y], allOf: [not: X, Z]]
  • Loading branch information
Phil Sturgeon authored Dec 18, 2018
2 parents 974538d + 08b682e commit aae1805
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
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');
});

0 comments on commit aae1805

Please sign in to comment.