redoc/src/utils/loadAndBundleSpec.ts

49 lines
1.6 KiB
TypeScript
Raw Normal View History

import type { Source, Document } from '@redocly/openapi-core';
// eslint-disable-next-line import/no-internal-modules
import { bundle } from '@redocly/openapi-core/lib/bundle';
// eslint-disable-next-line import/no-internal-modules
import { Config } from '@redocly/openapi-core/lib/config/config';
2018-07-23 13:22:24 +03:00
/* tslint:disable-next-line:no-implicit-dependencies */
2017-11-15 00:40:38 +03:00
import { convertObj } from 'swagger2openapi';
import { OpenAPISpec } from '../types';
import { IS_BROWSER } from './dom';
2017-11-15 00:40:38 +03:00
export async function loadAndBundleSpec(specUrlOrObject: object | string): Promise<OpenAPISpec> {
const config = new Config({});
const bundleOpts = {
config,
base: IS_BROWSER ? window.location.href : process.cwd()
}
if (IS_BROWSER) {
config.resolve.http.customFetch = global.fetch;
}
if (typeof specUrlOrObject === 'object' && specUrlOrObject !== null) {
bundleOpts['doc'] = {
source: { absoluteRef: '' } as Source,
parsed: specUrlOrObject
} as Document
} else {
bundleOpts['ref'] = specUrlOrObject;
}
const { bundle: { parsed } } = await bundle(bundleOpts);
return parsed.swagger !== undefined ? convertSwagger2OpenAPI(parsed) : parsed;
}
2017-11-15 00:40:38 +03:00
export function convertSwagger2OpenAPI(spec: any): Promise<OpenAPISpec> {
console.warn('[ReDoc Compatibility mode]: Converting OpenAPI 2.0 to OpenAPI 3.0');
2017-11-15 00:40:38 +03:00
return new Promise<OpenAPISpec>((resolve, reject) =>
2020-07-25 19:06:22 +03:00
convertObj(spec, { patch: true, warnOnly: true, text: '{}', anchors: true }, (err, res) => {
2017-11-15 00:40:38 +03:00
// TODO: log any warnings
if (err) {
return reject(err);
}
resolve(res && (res.openapi as any));
}),
);
}