Skip to content

Commit

Permalink
Merge pull request #2023 from kaioduarte/perf/lazy-load-swagger-ui
Browse files Browse the repository at this point in the history
perf(swagger-module): lazy load swagger-ui-dist module
  • Loading branch information
kamilmysliwiec committed Sep 1, 2022
2 parents 69df9c8 + 857a2d8 commit 1dc851c
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
3 changes: 2 additions & 1 deletion lib/swagger-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { SwaggerScanner } from './swagger-scanner';
import {
buildSwaggerHTML,
buildSwaggerInitJS,
swaggerAssetsAbsoluteFSPath
getSwaggerAssetsAbsoluteFSPath
} from './swagger-ui';
import { assignTwoLevelsDeep } from './utils/assign-two-levels-deep';
import { getGlobalPrefix } from './utils/get-global-prefix';
Expand Down Expand Up @@ -44,6 +44,7 @@ export class SwaggerModule {

private static serveStatic(finalPath: string, app: INestApplication) {
const httpAdapter = app.getHttpAdapter();
const swaggerAssetsAbsoluteFSPath = getSwaggerAssetsAbsoluteFSPath();

if (httpAdapter && httpAdapter.getType() === 'fastify') {
(app as NestFastifyApplication).useStaticAssets({
Expand Down
16 changes: 13 additions & 3 deletions lib/swagger-ui/swagger-ui.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import * as swaggerUi from 'swagger-ui-dist';
import { favIconHtml, htmlTemplateString, jsTemplateString } from './constants';
import { OpenAPIObject, SwaggerCustomOptions } from '../interfaces';
import { buildJSInitOptions } from './helpers';
Expand All @@ -21,10 +20,21 @@ export function buildSwaggerInitJS(
return jsTemplateString.replace('<% swaggerOptions %>', jsInitOptions);
}

let swaggerAssetsAbsoluteFSPath: string | undefined;

/**
* Stores absolute path to swagger-ui assets
* Returns the absolute path to swagger-ui assets.
*/
export const swaggerAssetsAbsoluteFSPath = swaggerUi.getAbsoluteFSPath();
export function getSwaggerAssetsAbsoluteFSPath() {
if (!swaggerAssetsAbsoluteFSPath) {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const swaggerUi = require('swagger-ui-dist');
swaggerAssetsAbsoluteFSPath = swaggerUi.getAbsoluteFSPath();
}

return swaggerAssetsAbsoluteFSPath;
}

/**
* Used to build swagger-ui custom html
*/
Expand Down

0 comments on commit 1dc851c

Please sign in to comment.