Skip to content

Instantly share code, notes, and snippets.

@moshewe
Last active April 24, 2023 10:52
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moshewe/99b54fdac1ab7c6b9f9b292324814beb to your computer and use it in GitHub Desktop.
Save moshewe/99b54fdac1ab7c6b9f9b292324814beb to your computer and use it in GitHub Desktop.
This script generates the swagger spec for a given NestJS Module. It takes the app's path, version and module name as parameters, with optionals for
import * as fs from 'fs';
import { NestFactory } from '@nestjs/core';
import { DocumentBuilder, SwaggerDocument, SwaggerModule } from '@nestjs/swagger';
import * as commander from 'commander';
const program = new commander.Command();
program
.name('single-app-swagger-json-generator')
.arguments('--app-path <app-path> --app-version <app-version>')
.requiredOption('-a, --app-path <path>', 'path to app\'s folder')
.requiredOption('-v, --app-version <version>', 'app\'s version')
.option('-m, --module-name <module>', 'module name')
.option('-n, --app-name <app-name>', 'app\'s name')
.option('-o, --output-dir <output-dir>', 'output directory to write the swagger spec to');
program.parse(process.argv);
const outputDir = program.outputDir || '.';
const importPath = `${process.cwd()}/${program.appPath}`;
(async () => {
const importedObject = await import(importPath);
const appModule =
program.moduleName ? importedObject[program.moduleName] :
importedObject.default;
const appName = program.appName || appModule.name;
const swaggerBaseConfig = new DocumentBuilder()
.setSchemes('https')
.setTitle(`${appName} API`)
.setDescription(`Auto-generated for app ${appName}.`)
.addBearerAuth()
.setVersion(program.appVersion)
.build();
const app = await NestFactory.create(appModule);
const document: SwaggerDocument = SwaggerModule.createDocument(app, swaggerBaseConfig);
fs.writeFileSync(`${outputDir}/${appName}.json`, JSON.stringify(document));
})();
@wesharper
Copy link

Is there a good way to integrate the swagger CLI plugin as an AST transformer with something like this?

@celso-alexandre
Copy link

Is there a good way to integrate the swagger CLI plugin as an AST transformer with something like this?

Would like to know that too

@moshewe
Copy link
Author

moshewe commented Dec 21, 2022

Haven't touched upon this in a few years, feel free to experiment and update everyone here...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment