Skip to content

Commit

Permalink
improve integration
Browse files Browse the repository at this point in the history
  • Loading branch information
magicmatatjahu committed Nov 7, 2022
1 parent 9bba8a0 commit 976d861
Show file tree
Hide file tree
Showing 6 changed files with 4,925 additions and 6,069 deletions.
7 changes: 5 additions & 2 deletions cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const path = require('path');
const os = require('os');
const program = require('commander');
const xfs = require('fs.extra');
const { DiagnosticSeverity } = require('@asyncapi/parser/cjs');
const packageInfo = require('./package.json');
const Generator = require('./lib/generator');
const Watcher = require('./lib/watcher');
Expand Down Expand Up @@ -64,8 +65,10 @@ const mapBaseUrlParser = v => {
const showError = err => {
console.error(red('Something went wrong:'));
console.error(red(err.stack || err.message));
if (err.errors) console.error(red(JSON.stringify(err.errors)));
if (err.validationErrors) console.error(red(JSON.stringify(err.validationErrors, null, 4)));
if (err.diagnostics) {
const errorDiagnostics = err.diagnostics.filter(diagnostic => diagnostic.severity === DiagnosticSeverity.Error);
console.error(red(`Errors:\n${JSON.stringify(errorDiagnostics, undefined, 2)}`));
}
};
const showErrorAndExit = err => {
showError(err);
Expand Down
10 changes: 8 additions & 2 deletions lib/generator.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ const {
getTemplateDetails,
convertCollectionToObject,
} = require('./utils');
const { getParser, usesNewAPI, getProperApiDocument } = require('./parser');
const { getParser, usesNewAPI, getProperApiDocument, convertOldOptionsToNew } = require('./parser');
const { registerFilters } = require('./filtersRegistry');
const { registerHooks } = require('./hooksRegistry');

Expand Down Expand Up @@ -263,7 +263,13 @@ class Generator {

/** @type {AsyncAPIDocument} Parsed AsyncAPI schema. See {@link https://github.com/asyncapi/parser-js/blob/master/API.md#module_@asyncapi/parser+AsyncAPIDocument|AsyncAPIDocument} for details on object structure. */
const parser = getParser(this);
const { document, diagnostics } = await parser.parse(asyncapiString, parseOptions);
const newParseOptions = convertOldOptionsToNew(parseOptions, this);
const { document, diagnostics } = await parser.parse(asyncapiString, newParseOptions);
if (!document) {
const err = new Error('Input is not a corrent AsyncAPI document so it cannot be processed.');
err.diagnostics = diagnostics;
throw err;
}
return this.generate(document);
}

Expand Down
60 changes: 59 additions & 1 deletion lib/parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,37 @@ parser.getProperApiDocument = (asyncapiDocument, templateConfig) => {
return parser.usesNewAPI(templateConfig) ? asyncapiDocument : convertToOldAPI(asyncapiDocument);
}

// The new options for the v2 Parser are different from those for the v1 version, but in order not to release Generator v2, we are converting the old options of Parser to the new ones.
parser.convertOldOptionsToNew = (oldOptions, generator) => {
if (!oldOptions) return;
const newOptions = {};

if (typeof oldOptions.path === 'string') {
newOptions.source = oldOptions.path;
}
if (typeof oldOptions.applyTraits === 'boolean') {
newOptions.applyTraits = oldOptions.applyTraits;
}

const resolvers = oldOptions.resolve;
if (resolvers) {
const convertedResolvers = convertResolvers(resolvers);
if (convertedResolvers) {
let mapBaseResolvers = [];
if (generator && generator.mapBaseUrlToFolder && generator.mapBaseUrlToFolder.url) {
mapBaseResolvers = getMapBaseUrlToFolderResolvers(generator.mapBaseUrlToFolder);
}

newOptions.__unstable = {};
newOptions.__unstable.resolver = {
resolvers: [...mapBaseResolvers, ...convertOldResolvers(resolvers)],
}
}
}

return newOptions;
}

/**
* Creates a custom resolver that maps urlToFolder.url to urlToFolder.folder
* Building your custom resolver is explained here: https://apitools.dev/json-schema-ref-parser/docs/plugins/resolvers.html
Expand All @@ -49,7 +80,7 @@ parser.getProperApiDocument = (asyncapiDocument, templateConfig) => {
* @param {object} urlToFolder to resolve url e.g. https://schema.example.com/crm/ to a folder e.g. ./test/docs/.
* @return {{read(*, *, *): Promise<unknown>, canRead(*): boolean, order: number}}
*/
getMapBaseUrlToFolderResolvers = ({ url: baseUrl, folder: baseDir }) => {
function getMapBaseUrlToFolderResolvers({ url: baseUrl, folder: baseDir }) {
const resolver = {
order: 1,
canRead: true,
Expand Down Expand Up @@ -78,3 +109,30 @@ getMapBaseUrlToFolderResolvers = ({ url: baseUrl, folder: baseDir }) => {
{ schema: 'https', ...resolver, },
];
};

function convertOldResolvers(resolvers = {}) {
if (Object.keys(resolvers).length === 0) return;

return Object.entries(resolvers).map(([protocol, resolver]) => {
const canRead = resolver.canRead;

return {
schema: protocol,
order: resolver.order || 0,
canRead: (uri) => {
const value = uri.valueOf();
if (typeof canRead === 'boolean') return canRead;
if (typeof canRead === 'string') return canRead === value;
if (Array.isArray(canRead)) return canRead.includes(value);
if (canRead instanceof RegExp) return canRead.test(value);
if (typeof canRead === 'function') {
return canRead({ url: value, extension: uri.suffix() });
}
return false;
},
read: (uri) => {
return resolver.read({ url: uri.valueOf(), extension: uri.suffix() });
}
}
});
}
Loading

0 comments on commit 976d861

Please sign in to comment.