* Load swagger specs from the given url or file path; handle yml or json * @param {String} specUrlStr The url or file path to the swagger spec
(specUrlStr, {log, validate} = {})
| 17 | * @param {String} specUrlStr The url or file path to the swagger spec |
| 18 | */ |
| 19 | async function loadSpec(specUrlStr, {log, validate} = {}) { |
| 20 | if (typeof log === 'function') { |
| 21 | log(chalk.blue('Loading ' + specUrlStr + '...')); |
| 22 | } |
| 23 | const parser = new SwaggerParser(); |
| 24 | let spec = await parser.parse(specUrlStr); |
| 25 | if (spec.swagger === '2.0') { |
| 26 | debugJson('Swagger spec loaded: ', spec); |
| 27 | spec = (await swagger2openapi.convertObj(spec, {patch: true})).openapi; |
| 28 | debugJson('OpenAPI spec converted from Swagger: ', spec); |
| 29 | } else if (spec.openapi) { |
| 30 | debugJson('OpenAPI spec loaded: ', spec); |
| 31 | } |
| 32 | |
| 33 | spec = cloneSpecObject(spec); |
| 34 | |
| 35 | // Validate and deference the spec |
| 36 | if (validate) { |
| 37 | spec = await parser.validate(spec, { |
| 38 | dereference: { |
| 39 | circular: true, // Allow circular $refs |
| 40 | }, |
| 41 | validate: { |
| 42 | spec: true, // Don't validate against the Swagger spec |
| 43 | }, |
| 44 | }); |
| 45 | } else { |
| 46 | try { |
| 47 | spec = await parser.dereference(spec); |
| 48 | } catch (error) { |
| 49 | // If returns http unauthorized error, ignore resolving external ref$ pointer |
| 50 | if (error instanceof ResolverError) { |
| 51 | spec = await parser.dereference(spec, {resolve: {external: false}}); |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | return spec; |
| 57 | } |
| 58 | |
| 59 | async function loadAndBuildSpec( |
| 60 | url, |
no test coverage detected