Skip to content

Commit 304638c

Browse files
committed
clean up the schemas to remove empty objects
1 parent 1550880 commit 304638c

File tree

1 file changed

+27
-15
lines changed

1 file changed

+27
-15
lines changed

src/Convertor.js

Lines changed: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
'use strict'
22

3-
const traverse = require('json-schema-traverse');
3+
const traverse = require('json-schema-traverse')
4+
const {v4: uuid} = require('uuid')
45

56
class Convertor {
67
constructor(schema) {
@@ -78,25 +79,36 @@ class Convertor {
7879

7980
traverse(this.schema, traversal)
8081

82+
for (const [key, value] of Object.entries(this.referencedSchemas)) {
83+
const path = value.split('/').slice(1)
84+
const pathKey = path.pop()
85+
delete path.reduce((previous, current) => previous[current], this.schema)[pathKey]
86+
}
87+
88+
this.removeEmpty(this.schema)
89+
8190
if (Object.keys(this.components).includes('main') === false) {
82-
// for (const [key, value] of Object.entries(this.referencedSchemas)) {
83-
// const path = value.split('/')
84-
// path.shift()
85-
// delete this.schema[path]
86-
// // const objPath = path.join('.')
87-
// // const newField = objPath.split('.').reduce((p,c)=>p&&p[c], this.schema)
88-
// // delete this.schema
89-
// }
90-
// console.log(this.schema)
91-
92-
delete this.schema.definitions
93-
// if (this.schema.$schema) {
94-
// delete this.schema.$schema;
95-
// }
9691
Object.assign(this.components.schemas, {'main': this.schema})
92+
} else {
93+
Object.assign(this.components.schemas, {[`main-${uuid()}`]: this.schema})
9794
}
95+
9896
return this.components
9997
}
98+
99+
removeEmpty(schema) {
100+
Object.keys(schema).forEach(key => {
101+
if (schema[key]
102+
&& typeof schema[key] === 'object'
103+
&& this.removeEmpty(schema[key]) === null) {
104+
delete schema[key]
105+
}
106+
})
107+
108+
if (Object.keys(schema).length === 0) {
109+
return null
110+
}
111+
}
100112
}
101113

102114
module.exports = Convertor

0 commit comments

Comments
 (0)