Skip to content
Permalink
Browse files

Fix for objects and arrays with `null` allowed using `anyOf`

  • Loading branch information
Ajaxy committed Sep 11, 2018
1 parent 39e7028 commit 700a36fe5455fbf603c3b64a5cd8fa2b5bcc3de1
Showing with 63 additions and 8 deletions.
  1. +12 −8 lib/index.js
  2. +51 −0 tests/all.test.js
@@ -20,17 +20,19 @@ function castProp(value, propertyDef) {
return null;
}

switch (resolveType(propertyDef)) {
const realDef = findNotNullDef(propertyDef);

switch (resolveType(realDef)) {
case 'integer':
return parseInt(value, 10) || 0;
case 'number':
return parseFloat(value) || 0;
case 'boolean':
return value !== 'false';
case 'array':
return Array.isArray(value) ? value.map(member => castProp(member, propertyDef.items)) : undefined;
return Array.isArray(value) ? value.map(member => castProp(member, realDef.items)) : undefined;
case 'object':
return typeof value === 'object' ? castWithSchema(value, propertyDef) : undefined;
return typeof value === 'object' ? castWithSchema(value, realDef) : undefined;
default:
return value;
}
@@ -51,7 +53,7 @@ function isNullAllowed(propertyDef) {
}

function resolveType(propertyDef) {
const { type, anyOf } = propertyDef;
const { type } = propertyDef;

if (typeof type === 'string') {
return type;
@@ -61,11 +63,13 @@ function resolveType(propertyDef) {
return type.find(t => t !== 'null');
}

if (anyOf) {
return anyOf.find(({ type: t }) => t !== 'null').type;
}

return null;
}

function findNotNullDef(propertyDef) {
return propertyDef.anyOf
? propertyDef.anyOf.find(({ type: t }) => t !== 'null')
: propertyDef;
}

module.exports = castWithSchema;
@@ -21,13 +21,20 @@ describe('All', () => {
l3: 'true',
l4: 'false',
},
l2: { // object when `null` allowed
l1: 'value',
l2: '777',
l3: 'true',
l4: 'false',
},
m: 'true', // schema with types array
n: 'null', // `null` allowed using types array
o: 'true', // schema with `anyOf`
p: 'null', // null allowed with `anyOf`
q: 'invalid-number',
r: 'invalid-object',
s: ['777', '7.77', 'invalid-number'],
s2: ['777', '7.77', 'invalid-number'], // array when `null` allowed
t: {}, // invalid array
u: 'value', // missing schema type
v: 'value', // missing type,
@@ -91,6 +98,30 @@ describe('All', () => {
},
},
},
l2: {
anyOf: [
{
type: 'object',
properties: {
l1: {
type: 'string',
},
l2: {
type: 'number',
},
l3: {
type: 'boolean',
},
l4: {
type: 'boolean',
},
},
},
{
type: 'null',
},
],
},
m: {
type: ['boolean', 'null'],
},
@@ -121,6 +152,19 @@ describe('All', () => {
type: 'number',
},
},
s2: {
anyOf: [
{
type: 'array',
items: {
type: 'number',
},
},
{
type: 'null',
},
],
},
t: {
type: 'array',
items: {
@@ -160,13 +204,20 @@ describe('All', () => {
l3: true,
l4: false,
},
l2: {
l1: 'value',
l2: 777,
l3: true,
l4: false,
},
m: true,
n: null,
o: true,
p: null,
q: 0,
r: undefined,
s: [777, 7.77, 0],
s2: [777, 7.77, 0],
t: undefined,
u: 'value',
v: 'value',

0 comments on commit 700a36f

Please sign in to comment.
You can’t perform that action at this time.