Skip to content

Commit

Permalink
feat(resolve): add ApiDOM OpenAPI 3.1.0 JSON parser
Browse files Browse the repository at this point in the history
Refs #2717
  • Loading branch information
char0n committed Jan 23, 2023
1 parent db4737f commit dc5b833
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@
"@babel/runtime-corejs3": "^7.11.2",
"@swagger-api/apidom-core": "^0.59.0",
"@swagger-api/apidom-reference": "^0.59.0",
"@swagger-api/apidom-ns-openapi-3-1": "^0.59.0",
"cookie": "~0.5.0",
"cross-fetch": "^3.1.5",
"deepmerge": "~4.2.2",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/* eslint-disable camelcase */
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 OpenApiJson3_1Parser = Parser.compose(Parser, {
props: {
name: 'openapi-json-3-1-swagger-client',
fileExtensions: ['.json'],
mediaTypes: new OpenAPIMediaTypes(
...mediaTypes.filterByFormat('generic'),
...mediaTypes.filterByFormat('json')
),
detectionRegExp: /"openapi"\s*:\s*"(?<version_json>3\.1\.(?:[1-9]\d*|0))"/,
},
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();
JSON.parse(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-json-3-1-swagger-client parser plugin doesn't support sourceMaps option"
);
}

const source = file.toString();

try {
const pojo = JSON.parse(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 OpenApiJson3_1Parser;
/* eslint-enable camelcase */

0 comments on commit dc5b833

Please sign in to comment.