Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: enable openapi generator to include & exclude specific controllers #10204

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 21 additions & 0 deletions packages/cli/.yo-rc.json
Original file line number Diff line number Diff line change
Expand Up @@ -975,6 +975,27 @@
"name": "promote-anonymous-schemas",
"hide": false
},
"readonly": {
"description": "Generate only GET endpoints.",
"required": false,
"type": "Boolean",
"name": "readonly",
"hide": false
},
"exclude": {
"description": "Exclude endpoints with provided regex.",
"required": false,
"type": "String",
"name": "exclude",
"hide": false
},
"include": {
"description": "Only include endpoints with provided regex.",
"required": false,
"type": "String",
"name": "include",
"hide": false
},
"config": {
"type": "String",
"alias": "c",
Expand Down
118 changes: 118 additions & 0 deletions packages/cli/generators/openapi/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,24 @@ module.exports = class OpenApiGenerator extends BaseGenerator {
type: Boolean,
});

this.option('readonly', {
description: g.f('Generate only GET endpoints.'),
required: false,
type: Boolean,
});

this.option('exclude', {
description: g.f('Exclude endpoints with provided regex.'),
required: false,
type: String,
});

this.option('include', {
description: g.f('Only include endpoints with provided regex.'),
required: false,
type: String,
});

return super._setupGenerator();
}

Expand Down Expand Up @@ -211,6 +229,62 @@ module.exports = class OpenApiGenerator extends BaseGenerator {
}
}

async askForReadonly() {
if (this.shouldExit()) return;
const prompts = [
{
name: 'readonly',
message: g.f('Generate only GET endpoints.'),
when: false,
default: false,
},
];
const answers = await this.prompt(prompts);
if (answers.readonly) {
this.options.readonly = answers.readonly;
}
}

async askForExclude() {
if (this.shouldExit()) return;
const prompts = [
{
name: 'exclude',
message: g.f('Exclude endpoints with provided regex.'),
when: false,
default: false,
},
];
const answers = await this.prompt(prompts);
if (answers.exclude) {
const excludes = answers.exclude.split(',');
this.excludings = [];
excludes.forEach(exclude => {
this.excludings.push(exclude);
});
}
}

async askForInclude() {
if (this.shouldExit()) return;
const prompts = [
{
name: 'include',
message: g.f('Only include endpoints with provided regex.'),
when: false,
default: false,
},
];
const answers = await this.prompt(prompts);
if (answers.include) {
const includes = answers.include.split(',');
this.includings = [];
includes.forEach(include => {
this.includings.push(include);
});
}
}

async askForSpecUrlOrPath() {
if (this.shouldExit()) return;
if (this.dataSourceInfo && this.dataSourceInfo.specPath) {
Expand All @@ -236,11 +310,55 @@ module.exports = class OpenApiGenerator extends BaseGenerator {

async loadAndBuildApiSpec() {
if (this.shouldExit()) return;
if (this.options.exclude && this.options.include) {
this.exit(
new Error('We cannot have include and exclude at the same time.'),
);
}
try {
let includings = [];
let excludings = [];
if (this.options.exclude) {
excludings = this.options.exclude.split(',');
}
if (this.options.include) {
includings = this.options.include.split(',');
}
if (!this.includings) this.includings = [];
includings.forEach(including => {
if (including.includes(':')) {
const splitedInclude = including.split(':');
const temp = {};
if (splitedInclude[0] === '*') {
temp[splitedInclude[1]] = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'];
this.includings.push(temp);
} else {
temp[splitedInclude[1]] = [splitedInclude[0]];
this.includings.push(temp);
}
}
});
if (!this.excludings) this.excludings = [];
excludings.forEach(excluding => {
if (excluding.includes(':')) {
const splitedExclude = excluding.split(':');
const temp = {};
if (splitedExclude[0] === '*') {
temp[splitedExclude[1]] = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'];
this.excludings.push(temp);
} else {
temp[splitedExclude[1]] = [splitedExclude[0]];
this.excludings.push(temp);
}
}
});
const result = await loadAndBuildSpec(this.url, {
log: this.log,
validate: this.options.validate,
promoteAnonymousSchemas: this.options['promote-anonymous-schemas'],
readonly: this.options.readonly,
excludings: this.excludings,
includings: this.includings,
});
debugJson('OpenAPI spec', result.apiSpec);
Object.assign(this, result);
Expand Down
125 changes: 123 additions & 2 deletions packages/cli/generators/openapi/spec-loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const {debugJson, cloneSpecObject} = require('./utils');
const {generateControllerSpecs} = require('./spec-helper');
const {generateModelSpecs, registerNamedSchemas} = require('./schema-helper');
const {ResolverError} = require('@apidevtools/json-schema-ref-parser');
const openapiFilter = require('openapi-filter');

/**
* Load swagger specs from the given url or file path; handle yml or json
Expand Down Expand Up @@ -58,9 +59,19 @@ async function loadSpec(specUrlStr, {log, validate} = {}) {

async function loadAndBuildSpec(
url,
{log, validate, promoteAnonymousSchemas} = {},
{
log,
validate,
promoteAnonymousSchemas,
readonly,
excludings,
includings,
} = {},
) {
const apiSpec = await loadSpec(url, {log, validate});
let apiSpec = await loadSpec(url, {log, validate});

apiSpec = filterSpec(apiSpec, readonly, excludings, includings);

// First populate the type registry for named schemas
const typeRegistry = {
objectTypeMapping: new Map(),
Expand All @@ -77,6 +88,116 @@ async function loadAndBuildSpec(
};
}

function getIndiciesOf(searchStr, str, caseSensitive) {
const searchStrLen = searchStr.length;
if (searchStrLen === 0) {
return [];
}
let startIndex = 0,
index;
const indices = [];
if (!caseSensitive) {
str = str.toLowerCase();
searchStr = searchStr.toLowerCase();
}
while ((index = str.indexOf(searchStr, startIndex)) > -1) {
indices.push(index);
startIndex = index + searchStrLen;
}
return indices;
}

function insertAtIndex(str, substring, index) {
return str.slice(0, index) + substring + str.slice(index);
}

function applyFilters(specs, options) {
const openapiComponent = specs.components;
specs = openapiFilter.filter(specs, options);
specs.components = openapiComponent;
return specs;
}

function findIndexes(stringSpecs, regex) {
let result;
const indices = [];
while ((result = regex.exec(stringSpecs))) {
indices.push(result.index);
}
return indices;
}

function excludeOrIncludeSpec(specs, filter) {
Object.keys(filter).forEach(filterKey => {
const regex = new RegExp(filterKey, 'g');
const actions = filter[filterKey];
for (const key in specs.paths) {
if (Object.hasOwnProperty.call(specs.paths, key)) {
if (findIndexes(key, regex).length) {
if (specs.paths[key]) {
actions.forEach(action => {
action = action.toLowerCase();
if (specs.paths[key][action]) {
specs.paths[key][action]['x-filter'] = true;
}
});
}
}
}
}
});
return specs;
}

function readonlySpec(specs) {
let stringifiedSpecs = JSON.stringify(specs);
const excludeOps = ['"post":', '"patch":', '"put":', '"delete":'];
excludeOps.forEach(operator => {
let indices = getIndiciesOf(operator, stringifiedSpecs);
let indiciesCount = 0;
while (indiciesCount < indices.length) {
indices = getIndiciesOf(operator, stringifiedSpecs);
const index = indices[indiciesCount];
stringifiedSpecs = insertAtIndex(
stringifiedSpecs,
'"x-filter": true,',
index + operator.length + 1,
);
indiciesCount++;
}
});
return JSON.parse(stringifiedSpecs);
}

function filterSpec(specs, readonly, excludings, includings) {
const options = {
valid: true,
info: true,
strip: true,
flags: ['x-filter'],
servers: true,
inverse: false,
};
if (excludings && excludings.length) {
excludings.forEach(exclude => {
specs = excludeOrIncludeSpec(specs, exclude);
});
specs = applyFilters(specs, options);
}
if (includings && includings.length) {
includings.forEach(include => {
specs = excludeOrIncludeSpec(specs, include);
});
options.inverse = true;
specs = applyFilters(specs, options);
}
if (readonly) {
options.inverse = false;
specs = applyFilters(readonlySpec(specs), options);
}
return specs;
}

module.exports = {
loadSpec,
loadAndBuildSpec,
Expand Down
1 change: 1 addition & 0 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
"mkdirp": "^3.0.1",
"natural-compare": "^1.4.0",
"pacote": "^18.0.6",
"openapi-filter": "^3.2.3",
"pluralize": "^8.0.0",
"regenerate": "^1.4.2",
"semver": "^7.6.2",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1033,6 +1033,27 @@ exports[`cli saves command metadata to .yo-rc.json 1`] = `
"name": "promote-anonymous-schemas",
"hide": false
},
"readonly": {
"description": "Generate only GET endpoints.",
"required": false,
"type": "Boolean",
"name": "readonly",
"hide": false
},
"exclude": {
"description": "Exclude endpoints with provided regex.",
"required": false,
"type": "String",
"name": "exclude",
"hide": false
},
"include": {
"description": "Only include endpoints with provided regex.",
"required": false,
"type": "String",
"name": "include",
"hide": false
},
"config": {
"type": "String",
"alias": "c",
Expand Down
Loading
Loading