Skip to content

Commit

Permalink
feat(resolve): add ApiDOM OpenAPI 3.1.0 YAML 1.2 parser
Browse files Browse the repository at this point in the history
Refs #2717
  • Loading branch information
char0n committed Jan 23, 2023
1 parent dc5b833 commit 77504ec
Showing 1 changed file with 68 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/* eslint-disable camelcase */
import YAML from 'js-yaml';
import { ParseResultElement } from '@swagger-api/apidom-core';
import { ParserError, Parser } from '@swagger-api/apidom-reference/configuration/empty';
import {
mediaTypes,
OpenApi3_1Element,
OpenAPIMediaTypes,
} from '@swagger-api/apidom-ns-openapi-3-1';

// eslint-disable-next-line camelcase
const OpenApiYaml3_1Parser = Parser.compose(Parser, {
props: {
name: 'openapi-yaml-3-1-swagger-client',
fileExtensions: ['.yaml', '.yml'],
mediaTypes: new OpenAPIMediaTypes(
...mediaTypes.filterByFormat('generic'),
...mediaTypes.filterByFormat('yaml')
),
detectionRegExp:
/(?<YAML>^(["']?)openapi\2\s*:\s*(["']?)(?<version_yaml>3\.1\.(?:[1-9]\d*|0))\3(?:\s+|$))|(?<JSON>"openapi"\s*:\s*"(?<version_json>3\.1\.(?:[1-9]\d*|0))")/m,
},
methods: {
async canParse(file) {
const hasSupportedFileExtension =
this.fileExtensions.length === 0 ? true : this.fileExtensions.includes(file.extension);
const hasSupportedMediaType = this.mediaTypes.includes(file.mediaType);

if (!hasSupportedFileExtension) return false;
if (hasSupportedMediaType) return true;
if (!hasSupportedMediaType) {
try {
const source = file.toString();
YAML.load(source);
return this.detectionRegExp.test(source);
} catch (error) {
return false;
}
}
return false;
},
async parse(file) {
if (this.sourceMap) {
// eslint-disable-next-line no-console
console.warn(
"openapi-yaml-3-1-swagger-client parser plugin doesn't support sourceMaps option"
);
}

const source = file.toString();

try {
const pojo = YAML.load(source);
const element = OpenApi3_1Element.refract(pojo, this.refractorOpts);
const parseResultElement = new ParseResultElement();

element.classes.push('result');
parseResultElement.push(element);
return parseResultElement;
} catch (error) {
throw new ParserError(`Error parsing "${file.uri}"`, error);
}
},
},
});

export default OpenApiYaml3_1Parser;
/* eslint-enable camelcase */

0 comments on commit 77504ec

Please sign in to comment.