0

I can generate openapi.json from my Nestjs App with no DB connection with the script below.

When I'm trying the same with a nest/mongoose dependency I'm can't generate the json file without having a mongoDb connection open first. Does anyone have a trick to just generate the json file without having app initialized first?

import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import * as fs from 'fs';

import { AppModule } from './app.module';

async function generateOpenapiSpecs() {
  const app = await NestFactory.create(AppModule);

  app.useGlobalPipes(new ValidationPipe());

  const config = new DocumentBuilder()
    .setTitle('Sample Service')
    .setDescription('Api for stackoverflow')
    .setVersion('1.0')
    .build();

  const document = SwaggerModule.createDocument(app, config);

  fs.writeFileSync('./.apim/openapi.json', JSON.stringify(document, null, 2));
}
generateOpenapiSpecs();
Nooneelse
  • 127
  • 2
  • 11

1 Answers1

1

Don' know if this approach works for you but i solved it in two steps:

  • Create two separate modules one (API Module) with all the imports and controllers, providers etc without Mongo import, and other only with mongoose/mongo configuration (Mongo Module).
  • Create a Main Module imports this two modules (API Module, Mongo Module).
  • Main bootstrap uses Main Module to run the application.
  • Create a different module with db connection using mongodb-memory-server (MongoMemmory Module)
  • Create a Swagger Main Module including MongoMemmory Module and API Module
  • Swagger bootstrap uses Swagger Main Module to run swagger server using mongo in memmory.