Skip to content

Instantly share code, notes, and snippets.

@iTrooz
Last active October 11, 2025 16:05
Show Gist options
  • Save iTrooz/94b2254f808fbe6186b8b375eef0e3a5 to your computer and use it in GitHub Desktop.
Save iTrooz/94b2254f808fbe6186b8b375eef0e3a5 to your computer and use it in GitHub Desktop.
NestJS CLI tool to dump openapi.json
// Help: https://stackoverflow.com/questions/72852736/generating-swagger-json-file-without-running-nest-js-server
// NestJS 11
import * as path from 'path';
import { writeFileSync } from 'fs';
import { DataType, newDb } from 'pg-mem';
import { DataSource } from 'typeorm';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { Test } from '@nestjs/testing';
import { AppModule } from '../src/app.module';
async function dumpSwagger() {
// Setup in-memory Postgres
const db = newDb();
db.public.registerFunction({
name: 'current_database',
args: [],
returns: DataType.text,
implementation: () => 'localdb',
});
db.public.registerFunction({
name: 'version',
args: [],
returns: DataType.text,
implementation: () => '1',
});
const datasource = (await db.adapters.createTypeormDataSource({
type: 'postgres',
autoLoadEntities: true,
synchronize: true,
})) as DataSource;
await datasource.initialize();
await datasource.synchronize();
const moduleFixture = await Test.createTestingModule({
imports: [AppModule],
})
.overrideProvider(DataSource)
.useValue(datasource)
.compile();
let app = moduleFixture.createNestApplication();
// Create Swagger
const config = new DocumentBuilder()
.setTitle('NestJS App')
.setDescription('NestJS App description')
.setVersion('1.0')
.build();
const document = SwaggerModule.createDocument(app, config);
await app.close();
return document;
}
dumpSwagger().then(document => {
const jsonContent = JSON.stringify(document, null, 2);
const outputFilePath = process.argv[2];
if (outputFilePath) {
// Write to specified file
const resolvedPath = path.resolve(process.cwd(), outputFilePath);
writeFileSync(resolvedPath, jsonContent, 'utf8');
console.log(`Swagger JSON dumped to ${resolvedPath}`);
} else {
// Dump to stdout
console.log(jsonContent);
}
}).catch(err => {
console.error(err);
process.exit(1);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment