|
1 | 1 | 'use strict' |
2 | 2 |
|
3 | | -const traverse = require('json-schema-traverse'); |
| 3 | +const traverse = require('json-schema-traverse') |
| 4 | +const {v4: uuid} = require('uuid') |
4 | 5 |
|
5 | 6 | class Convertor { |
6 | 7 | constructor(schema) { |
@@ -78,25 +79,36 @@ class Convertor { |
78 | 79 |
|
79 | 80 | traverse(this.schema, traversal) |
80 | 81 |
|
| 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 | + |
81 | 90 | 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 | | - // } |
96 | 91 | Object.assign(this.components.schemas, {'main': this.schema}) |
| 92 | + } else { |
| 93 | + Object.assign(this.components.schemas, {[`main-${uuid()}`]: this.schema}) |
97 | 94 | } |
| 95 | + |
98 | 96 | return this.components |
99 | 97 | } |
| 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 | + } |
100 | 112 | } |
101 | 113 |
|
102 | 114 | module.exports = Convertor |
0 commit comments