1- const { isObject, isArray, isNumber, isString} = require ( './types' ) ;
1+ const { isObject, isArray, isNumber, isString, isUndefined } = require ( './types' ) ;
22
33/**
44 * Add property to object at certain position
@@ -18,14 +18,14 @@ function setInObject(obj, key, value, index) {
1818 for ( let prop in obj ) {
1919 if ( Object . prototype . hasOwnProperty . call ( obj , prop ) ) {
2020 // If the indexes match, add the new item
21- if ( i === index && isNumber ( index ) && key && value ) {
21+ if ( i === index && isNumber ( index ) && key && ! isUndefined ( value ) ) {
2222 dto [ key ] = value ;
2323 }
2424 // Add the current item in the loop to the temp obj
2525 dto [ prop ] = obj [ prop ] ;
2626
2727 // Add/overwrite item
28- if ( isString ( index ) && i === ordering . indexOf ( index ) && key && value ) {
28+ if ( isString ( index ) && i === ordering . indexOf ( index ) && key && ! isUndefined ( value ) ) {
2929 dto [ key ] = value ;
3030 }
3131 // Increase the count
@@ -40,7 +40,12 @@ function setInObject(obj, key, value, index) {
4040}
4141
4242/**
43- * Convert nullable property to type
43+ * converts:
44+ * `type: 'thing'` -> `type: ['thing']`
45+ * `type: 'thing', nullable: true` -> `type: ['thing', 'null']`
46+ * `anyOf: ['thing'], nullable: true` -> `anyOf: ['thing', {type: 'null'}]`
47+ * `oneOf: ['thing'], nullable: true` -> `oneOf: ['thing', {type: 'null'}]`
48+ *
4449 * @param {object } obj
4550 * @returns {* }
4651 */
@@ -49,12 +54,20 @@ function convertNullable(obj) {
4954 if ( obj . nullable === undefined ) return obj ;
5055
5156 let dto = JSON . parse ( JSON . stringify ( obj ) ) ; // Deep copy of the object
52- const types = [ dto . type . toString ( ) ] ;
53- if ( dto . nullable === true ) {
54- types . push ( 'null' ) ;
57+ // Update for 3.1
58+ if ( obj . type ) {
59+ const types = [ dto . type . toString ( ) ] ;
60+ if ( dto . nullable === true ) {
61+ types . push ( 'null' ) ;
62+ }
63+ dto = setInObject ( dto , 'type' , types , 'type' ) ;
64+ } else if ( dto . nullable === true && Array . isArray ( dto . oneOf ) ) {
65+ const withNullType = dto . oneOf . concat ( { type : 'null' } ) ;
66+ dto = setInObject ( dto , 'oneOf' , withNullType , 'oneOf' ) ;
67+ } else if ( dto . nullable === true && Array . isArray ( dto . anyOf ) ) {
68+ const withNullType = dto . anyOf . concat ( { type : 'null' } ) ;
69+ dto = setInObject ( dto , 'anyOf' , withNullType , 'anyOf' ) ;
5570 }
56- // Update 3.1 type
57- dto = setInObject ( dto , 'type' , types , 'type' ) ;
5871 // Remove 3.0 prop
5972 delete dto . nullable ;
6073 return dto ;
0 commit comments