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(swagger): JSON and YAML document endpoints customizable #2273

Merged
Merged
Show file tree
Hide file tree
Changes from 5 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
87 changes: 87 additions & 0 deletions e2e/express.e2e-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,4 +96,91 @@ describe('Express Swagger', () => {
expect(Object.keys(response.body).length).toBeGreaterThan(0);
});
});

describe('custom documents endpoints', () => {
const JSON_CUSTOM_URL = '/apidoc-json';
const YAML_CUSTOM_URL = '/apidoc-yaml';

beforeEach(async () => {
const swaggerDocument = SwaggerModule.createDocument(
app,
builder.build()
);
SwaggerModule.setup('api', app, swaggerDocument, {
jsonDocumentUrl: JSON_CUSTOM_URL,
yamlDocumentUrl: YAML_CUSTOM_URL
});

await app.init();
});

afterEach(async () => {
await app.close();
});

it('json document should be server in the custom url', async () => {
const response = await request(app.getHttpServer()).get(JSON_CUSTOM_URL);

expect(response.status).toEqual(200);
expect(Object.keys(response.body).length).toBeGreaterThan(0);
});

it('yaml document should be server in the custom url', async () => {
const response = await request(app.getHttpServer()).get(YAML_CUSTOM_URL);

expect(response.status).toEqual(200);
expect(response.text.length).toBeGreaterThan(0);
});
});

describe('custom documents endpoints with global prefix', () => {
let appGlobalPrefix: NestExpressApplication;

const GLOBAL_PREFIX = '/v1';
const JSON_CUSTOM_URL = '/apidoc-json';
const YAML_CUSTOM_URL = '/apidoc-yaml';

beforeEach(async () => {
appGlobalPrefix = await NestFactory.create<NestExpressApplication>(
ApplicationModule,
new ExpressAdapter(),
{ logger: false }
);
appGlobalPrefix.setGlobalPrefix(GLOBAL_PREFIX);

const swaggerDocument = SwaggerModule.createDocument(
appGlobalPrefix,
builder.build()
);
SwaggerModule.setup('api', appGlobalPrefix, swaggerDocument, {
useGlobalPrefix: true,
jsonDocumentUrl: JSON_CUSTOM_URL,
yamlDocumentUrl: YAML_CUSTOM_URL
});

await appGlobalPrefix.init();
});

afterEach(async () => {
await appGlobalPrefix.close();
});

it('json document should be server in the custom url', async () => {
const response = await request(appGlobalPrefix.getHttpServer()).get(
`${GLOBAL_PREFIX}${JSON_CUSTOM_URL}`
);

expect(response.status).toEqual(200);
expect(Object.keys(response.body).length).toBeGreaterThan(0);
});

it('yaml document should be server in the custom url', async () => {
const response = await request(appGlobalPrefix.getHttpServer()).get(
`${GLOBAL_PREFIX}${YAML_CUSTOM_URL}`
);

expect(response.status).toEqual(200);
expect(response.text.length).toBeGreaterThan(0);
});
});
});
89 changes: 89 additions & 0 deletions e2e/fastify.e2e-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,4 +99,93 @@ describe('Fastify Swagger', () => {
expect(Object.keys(response.body).length).toBeGreaterThan(0);
});
});

describe('custom documents endpoints', () => {
const JSON_CUSTOM_URL = '/apidoc-json';
const YAML_CUSTOM_URL = '/apidoc-yaml';

beforeEach(async () => {
const swaggerDocument = SwaggerModule.createDocument(
app,
builder.build()
);
SwaggerModule.setup('api', app, swaggerDocument, {
jsonDocumentUrl: JSON_CUSTOM_URL,
yamlDocumentUrl: YAML_CUSTOM_URL
});

await app.init();
await app.getHttpAdapter().getInstance().ready();
});

afterEach(async () => {
await app.close();
});

it('json document should be server in the custom url', async () => {
const response = await request(app.getHttpServer()).get(JSON_CUSTOM_URL);

expect(response.status).toEqual(200);
expect(Object.keys(response.body).length).toBeGreaterThan(0);
});

it('yaml document should be server in the custom url', async () => {
const response = await request(app.getHttpServer()).get(YAML_CUSTOM_URL);

expect(response.status).toEqual(200);
expect(response.text.length).toBeGreaterThan(0);
});
});

describe('custom documents endpoints with global prefix', () => {
let appGlobalPrefix: NestFastifyApplication;

const GLOBAL_PREFIX = '/v1';
const JSON_CUSTOM_URL = '/apidoc-json';
const YAML_CUSTOM_URL = '/apidoc-yaml';

beforeEach(async () => {
appGlobalPrefix = await NestFactory.create<NestFastifyApplication>(
ApplicationModule,
new FastifyAdapter(),
{ logger: false }
);
appGlobalPrefix.setGlobalPrefix(GLOBAL_PREFIX);

const swaggerDocument = SwaggerModule.createDocument(
appGlobalPrefix,
builder.build()
);
SwaggerModule.setup('api', appGlobalPrefix, swaggerDocument, {
useGlobalPrefix: true,
jsonDocumentUrl: JSON_CUSTOM_URL,
yamlDocumentUrl: YAML_CUSTOM_URL
});

await appGlobalPrefix.init();
await appGlobalPrefix.getHttpAdapter().getInstance().ready();
});

afterEach(async () => {
await appGlobalPrefix.close();
});

it('json document should be server in the custom url', async () => {
const response = await request(appGlobalPrefix.getHttpServer()).get(
`${GLOBAL_PREFIX}${JSON_CUSTOM_URL}`
);

expect(response.status).toEqual(200);
expect(Object.keys(response.body).length).toBeGreaterThan(0);
});

it('yaml document should be server in the custom url', async () => {
const response = await request(appGlobalPrefix.getHttpServer()).get(
`${GLOBAL_PREFIX}${YAML_CUSTOM_URL}`
);

expect(response.status).toEqual(200);
expect(response.text.length).toBeGreaterThan(0);
});
});
});
2 changes: 1 addition & 1 deletion lib/extra/swagger-shim.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,5 +165,5 @@ export function PickType() {
return () => {};
}
export function getSchemaPath() {
return () => ''
return () => '';
}
2 changes: 2 additions & 0 deletions lib/interfaces/swagger-custom-options.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,6 @@ export interface SwaggerCustomOptions {
validatorUrl?: string;
url?: string;
urls?: Record<'url' | 'name', string>[];
jsonDocumentUrl?: string;
yamlDocumentUrl?: string;
}
28 changes: 23 additions & 5 deletions lib/swagger-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { assignTwoLevelsDeep } from './utils/assign-two-levels-deep';
import { getGlobalPrefix } from './utils/get-global-prefix';
import { validatePath } from './utils/validate-path.util';
import { normalizeRelPath } from './utils/normalize-rel-path';
import { validateGlobalPrefix } from './utils/validate-global-prefix.util';

export class SwaggerModule {
public static createDocument(
Expand Down Expand Up @@ -67,7 +68,9 @@ export class SwaggerModule {
swaggerInitJS: string,
yamlDocument: string,
jsonDocument: string,
html: string
html: string,
jsonDocumentUrl: string,
yamlDocumentUrl: string
jcolladosp marked this conversation as resolved.
Show resolved Hide resolved
) {
httpAdapter.get(
normalizeRelPath(`${finalPath}/swagger-ui-init.js`),
Expand Down Expand Up @@ -118,12 +121,12 @@ export class SwaggerModule {
*/
}

httpAdapter.get(normalizeRelPath(`${finalPath}-json`), (req, res) => {
httpAdapter.get(normalizeRelPath(jsonDocumentUrl), (req, res) => {
res.type('application/json');
res.send(jsonDocument);
});

httpAdapter.get(normalizeRelPath(`${finalPath}-yaml`), (req, res) => {
httpAdapter.get(normalizeRelPath(yamlDocumentUrl), (req, res) => {
res.type('text/yaml');
res.send(yamlDocument);
});
Expand All @@ -137,7 +140,7 @@ export class SwaggerModule {
) {
const globalPrefix = getGlobalPrefix(app);
const finalPath = validatePath(
options?.useGlobalPrefix && globalPrefix && !globalPrefix.match(/^(\/?)$/)
options?.useGlobalPrefix && validateGlobalPrefix(globalPrefix)
? `${globalPrefix}${validatePath(path)}`
: path
);
Expand All @@ -146,6 +149,19 @@ export class SwaggerModule {
const yamlDocument = jsyaml.dump(document, { skipInvalid: true });
const jsonDocument = JSON.stringify(document);

const validatedGlobalPrefix =
options?.useGlobalPrefix && validateGlobalPrefix(globalPrefix)
? validatePath(globalPrefix)
: '';

const finalJSONDocumentPath = options?.jsonDocumentUrl
? `${validatedGlobalPrefix}${validatePath(options.jsonDocumentUrl)}`
: `${finalPath}-json`;

const finalYAMLDocumentPath = options?.yamlDocumentUrl
? `${validatedGlobalPrefix}${validatePath(options.yamlDocumentUrl)}`
: `${finalPath}-yaml`;

const baseUrlForSwaggerUI = normalizeRelPath(`./${urlLastSubdirectory}/`);

const html = buildSwaggerHTML(baseUrlForSwaggerUI, document, options);
Expand All @@ -159,7 +175,9 @@ export class SwaggerModule {
swaggerInitJS,
yamlDocument,
jsonDocument,
html
html,
finalJSONDocumentPath,
finalYAMLDocumentPath
);

SwaggerModule.serveStatic(finalPath, app);
Expand Down
7 changes: 3 additions & 4 deletions lib/type-helpers/intersection-type.helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { clonePluginMetadataFactory } from './mapped-types.utils';
const modelPropertiesAccessor = new ModelPropertiesAccessor();

type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (
k: infer I,
k: infer I
) => void
? I
: never;
Expand All @@ -39,7 +39,7 @@ export function IntersectionType<T extends Type[]>(...classRefs: T) {
const fields = modelPropertiesAccessor.getModelProperties(
classRef.prototype
);

inheritValidationMetadata(classRef, IntersectionClassType);
inheritTransformationMetadata(classRef, IntersectionClassType);

Expand All @@ -57,12 +57,11 @@ export function IntersectionType<T extends Type[]>(...classRefs: T) {
const decoratorFactory = ApiProperty(metadata);
decoratorFactory(IntersectionClassType.prototype, propertyKey);
});

});

const intersectedNames = classRefs.reduce((prev, ref) => prev + ref.name, '');
Object.defineProperty(IntersectionClassType, 'name', {
value: `Intersection${intersectedNames}`,
value: `Intersection${intersectedNames}`
});
return IntersectionClassType as Intersection<T>;
}
2 changes: 2 additions & 0 deletions lib/utils/validate-global-prefix.util.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const validateGlobalPrefix = (globalPrefix: string): boolean =>
globalPrefix && !globalPrefix.match(/^(\/?)$/);
8 changes: 6 additions & 2 deletions test/type-helpers/intersection-type.helper.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,11 @@ describe('IntersectionType', () => {
}
}

class UpdateUserDto extends IntersectionType(UserDto, CreateUserDto, AuthorityDto) {}
class UpdateUserDto extends IntersectionType(
UserDto,
CreateUserDto,
AuthorityDto
) {}

let modelPropertiesAccessor: ModelPropertiesAccessor;

Expand All @@ -52,7 +56,7 @@ describe('IntersectionType', () => {

describe('OpenAPI metadata', () => {
it('should return combined class', () => {
const prototype = (UpdateUserDto.prototype as any) as Type<unknown>;
const prototype = UpdateUserDto.prototype as any as Type<unknown>;

modelPropertiesAccessor.applyMetadataFactory(prototype);
expect(modelPropertiesAccessor.getModelProperties(prototype)).toEqual([
Expand Down