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: Add exclude as a complement to exclude. #1289

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
9 changes: 9 additions & 0 deletions e2e/src/bar/bar.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { Controller, Get } from '@nestjs/common';

@Controller('bar')
export class BarController {
@Get()
getBar() {
return 'bar';
}
}
7 changes: 7 additions & 0 deletions e2e/src/bar/bar.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { Module } from '@nestjs/common';
import { BarController } from './bar.controller';

@Module({
controllers: [BarController]
})
export class BarModule {}
9 changes: 9 additions & 0 deletions e2e/src/baz/baz.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { Controller, Get } from '@nestjs/common';

@Controller('baz')
export class BazController {
@Get()
getBaz() {
return 'baz';
}
}
7 changes: 7 additions & 0 deletions e2e/src/baz/baz.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { Module } from '@nestjs/common';
import { BazController } from './baz.controller';

@Module({
controllers: [BazController]
})
export class BazModule {}
9 changes: 9 additions & 0 deletions e2e/src/foo/foo.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { Controller, Get } from '@nestjs/common';

@Controller('foo')
export class FooController {
@Get()
getFoo() {
return 'foo';
}
}
7 changes: 7 additions & 0 deletions e2e/src/foo/foo.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { Module } from '@nestjs/common';
import { FooController } from './foo.controller';

@Module({
controllers: [FooController]
})
export class FooModule {}
9 changes: 9 additions & 0 deletions e2e/src/include-exclude.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { BarModule } from './bar/bar.module';
import { BazModule } from './baz/baz.module';
import { FooModule } from './foo/foo.module';

@Module({
imports: [FooModule, BarModule, BazModule]
})
export class IncludeExcludeModule {}
155 changes: 111 additions & 44 deletions e2e/validate-schema.e2e-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,56 +2,123 @@ import { NestFactory } from '@nestjs/core';
import { writeFileSync } from 'fs';
import { join } from 'path';
import * as SwaggerParser from 'swagger-parser';
import { DocumentBuilder, OpenAPIObject, SwaggerModule } from '../lib';
import {
DocumentBuilder,
OpenAPIObject,
SwaggerDocumentOptions,
SwaggerModule
} from '../lib';
import { ApplicationModule } from './src/app.module';
import { BarModule } from './src/bar/bar.module';
import { FooModule } from './src/foo/foo.module';
import { IncludeExcludeModule } from './src/include-exclude.module';

describe('Validate OpenAPI schema', () => {
let document: OpenAPIObject;
describe('general schema', () => {
let document: OpenAPIObject;
beforeEach(async () => {
const app = await NestFactory.create(ApplicationModule, {
logger: false
});
app.setGlobalPrefix('api/');

beforeEach(async () => {
const app = await NestFactory.create(ApplicationModule, {
logger: false
const options = new DocumentBuilder()
.setTitle('Cats example')
.setDescription('The cats API description')
.setVersion('1.0')
.setBasePath('api')
.addTag('cats')
.addBasicAuth()
.addBearerAuth()
.addOAuth2()
.addApiKey()
.addApiKey({ type: 'apiKey' }, 'key1')
.addApiKey({ type: 'apiKey' }, 'key2')
.addCookieAuth()
.addSecurityRequirements('bearer')
.addSecurityRequirements({ basic: [], cookie: [] })
.build();

document = SwaggerModule.createDocument(app, options);
});

it('should produce a valid OpenAPI 3.0 schema', async () => {
const doc = JSON.stringify(document, null, 2);
writeFileSync(join(__dirname, 'api-spec.json'), doc);

try {
let api = await SwaggerParser.validate(document as any);
console.log(
'API name: %s, Version: %s',
api.info.title,
api.info.version
);
expect(api.info.title).toEqual('Cats example');
expect(
api.paths['/api/cats']['get']['x-codeSamples'][0]['lang']
).toEqual('JavaScript');
} catch (err) {
console.log(doc);
expect(err).toBeUndefined();
}
});
app.setGlobalPrefix('api/');

const options = new DocumentBuilder()
.setTitle('Cats example')
.setDescription('The cats API description')
.setVersion('1.0')
.setBasePath('api')
.addTag('cats')
.addBasicAuth()
.addBearerAuth()
.addOAuth2()
.addApiKey()
.addApiKey({ type: 'apiKey' }, 'key1')
.addApiKey({ type: 'apiKey' }, 'key2')
.addCookieAuth()
.addSecurityRequirements('bearer')
.addSecurityRequirements({ basic: [], cookie: [] })
.build();

document = SwaggerModule.createDocument(app, options);
});

it('should produce a valid OpenAPI 3.0 schema', async () => {
const doc = JSON.stringify(document, null, 2);
writeFileSync(join(__dirname, 'api-spec.json'), doc);

try {
let api = await SwaggerParser.validate(document as any);
console.log(
'API name: %s, Version: %s',
api.info.title,
api.info.version
);
expect(api.info.title).toEqual('Cats example');
expect(api.paths['/api/cats']['get']['x-codeSamples'][0]['lang']).toEqual(
'JavaScript'
);
} catch (err) {
console.log(doc);
expect(err).toBeUndefined();
}
describe('include/exclude', () => {
const createDocument = async (swaggerOptions?: SwaggerDocumentOptions) => {
const app = await NestFactory.create(IncludeExcludeModule, {
logger: false
});
app.setGlobalPrefix('api/');

const options = new DocumentBuilder()
.setTitle('Include/Exclude')
.setVersion('1.0')
.setBasePath('api')
.build();

return SwaggerModule.createDocument(app, options, swaggerOptions);
};

it('should exclude specified modules', async () => {
const doc = await createDocument({
exclude: [FooModule]
});
const keys = Object.keys(doc.paths).sort();
expect(keys).toEqual(['/api/bar', '/api/baz']);
});

it('should exclude multiple modules', async () => {
const doc = await createDocument({
exclude: [FooModule, BarModule]
});
const keys = Object.keys(doc.paths).sort();
expect(keys).toEqual(['/api/baz']);
});

it('should include specified modules', async () => {
const doc = await createDocument({
include: [FooModule]
});
const keys = Object.keys(doc.paths).sort();
expect(keys).toEqual(['/api/foo']);
});

it('should include multiple modules', async () => {
const doc = await createDocument({
include: [FooModule, BarModule]
});
const keys = Object.keys(doc.paths).sort();
expect(keys).toEqual(['/api/bar', '/api/foo']);
});

it('should throw if include/exclude are specified together', async () => {
await expect(async () => {
await createDocument({
include: [FooModule],
exclude: [BarModule]
});
}).rejects.toThrow('Cannot specify both include and exclude together');
});
});
});
7 changes: 6 additions & 1 deletion lib/interfaces/swagger-document-options.interface.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
export interface SwaggerDocumentOptions {
/**
* List of modules to include in the specification
* List of modules to include in the specification. Cannot be used if `exclude` is specified
*/
include?: Function[];

/**
* List of modules to exclude in the specification. Cannot be used if `include` is specified
*/
exclude?: Function[];

/**
* Additional, extra models that should be inspected and included in the specification
*/
Expand Down
26 changes: 18 additions & 8 deletions lib/swagger-scanner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { MODULE_PATH } from '@nestjs/common/constants';
import { NestContainer } from '@nestjs/core/injector/container';
import { InstanceWrapper } from '@nestjs/core/injector/instance-wrapper';
import { Module } from '@nestjs/core/injector/module';
import { extend, flatten, isEmpty, reduce } from 'lodash';
import { extend, flatten, reduce } from 'lodash';
import { OpenAPIObject, SwaggerDocumentOptions } from './interfaces';
import {
ReferenceObject,
Expand Down Expand Up @@ -31,6 +31,7 @@ export class SwaggerScanner {
const {
deepScanRoutes,
include: includedModules = [],
exclude: excludedModules = [],
extraModels = [],
ignoreGlobalPrefix = false,
operationIdFactory
Expand All @@ -39,7 +40,8 @@ export class SwaggerScanner {
const container: NestContainer = (app as any).container;
const modules: Module[] = this.getModules(
container.getModules(),
includedModules
includedModules,
excludedModules
);
const globalPrefix = !ignoreGlobalPrefix
? stripLastSlash(this.getGlobalPrefix(app))
Expand Down Expand Up @@ -107,14 +109,22 @@ export class SwaggerScanner {

public getModules(
modulesContainer: Map<string, Module>,
include: Function[]
include: readonly Function[],
exclude: readonly Function[]
): Module[] {
if (!include || isEmpty(include)) {
return [...modulesContainer.values()];
const modules = [...modulesContainer.values()];
if (include.length === 0 && exclude.length === 0) {
return modules;
}
return [...modulesContainer.values()].filter(({ metatype }) =>
include.some((item) => item === metatype)
);

if (include.length && exclude.length) {
throw new Error('Cannot specify both include and exclude together');
}

const isInclude = include.length > 0;
const set = new Set(isInclude ? include : exclude);

return modules.filter(({ metatype }) => set.has(metatype) === isInclude);
}

public addExtraModels(schemas: SchemaObject[], extraModels: Function[]) {
Expand Down