|
1 | | -import { dereference } from '@jdw/jst'; |
| 1 | +import { JSONSchema7 } from 'json-schema'; |
2 | 2 | // tslint:disable-next-line no-submodule-imports |
3 | 3 | import { validateSync as openApiValidatorSync } from 'swagger2openapi/validate'; |
4 | 4 | import * as uuid from 'uuid'; |
| 5 | + |
5 | 6 | import { IDefinition, IDefinitionConfig, IOperation, IParameterConfig, IServerlessFunctionConfig } from './types'; |
6 | | -import { clone, isIterable, merge } from './utils'; |
| 7 | +import { clone, isIterable, merge, omit } from './utils'; |
7 | 8 |
|
8 | 9 | export class DefinitionGenerator { |
9 | 10 | // The OpenAPI version we currently validate against |
@@ -49,9 +50,16 @@ export class DefinitionGenerator { |
49 | 50 | continue; |
50 | 51 | } |
51 | 52 |
|
52 | | - this.definition.components.schemas[model.name] = this.cleanSchema( |
53 | | - dereference(model.schema), |
54 | | - ); |
| 53 | + for (const definitionName of Object.keys(model.schema.definitions || {})) { |
| 54 | + const definition = model.schema.definitions[definitionName]; |
| 55 | + if (typeof definition !== 'boolean') { |
| 56 | + this.definition.components.schemas[definitionName] = this.cleanSchema(this.updateReferences(definition)); |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + const schemaWithoutDefinitions = omit(model.schema, ['definitions']); |
| 61 | + |
| 62 | + this.definition.components.schemas[model.name] = this.cleanSchema(this.updateReferences(schemaWithoutDefinitions)); |
55 | 63 | } |
56 | 64 | } |
57 | 65 |
|
@@ -116,6 +124,28 @@ export class DefinitionGenerator { |
116 | 124 | return cleanedSchema; |
117 | 125 | } |
118 | 126 |
|
| 127 | + /** |
| 128 | + * Walks through the schema object recursively and updates references to point to openapi's components |
| 129 | + * @param schema JSON Schema Object |
| 130 | + */ |
| 131 | + private updateReferences (schema: JSONSchema7): JSONSchema7 { |
| 132 | + const cloned = clone(schema) as JSONSchema7; |
| 133 | + |
| 134 | + if (cloned.$ref) { |
| 135 | + cloned.$ref = cloned.$ref.replace('#/definitions', '#/components/schemas'); |
| 136 | + } else { |
| 137 | + for (const key of Object.getOwnPropertyNames(cloned)) { |
| 138 | + const value = cloned[key]; |
| 139 | + |
| 140 | + if (typeof value === 'object') { |
| 141 | + cloned[key] = this.updateReferences(value); |
| 142 | + } |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + return cloned; |
| 147 | + } |
| 148 | + |
119 | 149 | /** |
120 | 150 | * Generate Operation objects from the Serverless Config. |
121 | 151 | * |
|
0 commit comments