Swagger not working even the server is started in Nestjs app

56 Views Asked by At

I design this main.ts file and need to test the controllers with Swagger. I start:dev and all the server works fine, but cannot access via localhost:3000/docs/ws to enter Swagger UI. Here is the code:

//imported stuffs

async function docApi(app: NestExpressApplication) {
  const pathModule = {
    'docs/auth': AuthModule,
    'docs/client': ClientDomainModule,
    'docs/health': HealthModule,
    'docs/ws': WorkspaceModule,
  };

  const config = new DocumentBuilder()
    .setTitle('Booking API Documentation')
    .setDescription('Booking API Documentation')
    .setVersion('1.0')
    .addBearerAuth()
    .build();
  const css = await fs.readFileSync(pathLib.join(__dirname, '..', 'assets/css/swagger.css'), {
    encoding: 'utf8',
  });
  for (const [path, module] of Object.entries(pathModule)) {
    const document = SwaggerModule.createDocument(app, config, {
      deepScanRoutes: true,
      include: [module],
    });
    fs.writeFileSync(pathLib.join(__dirname, `./../${path}.sw.json`), JSON.stringify(document)); // <-- Save document to json file
    SwaggerModule.setup(path, app, document, {
      customCss: css,
      customSiteTitle: 'Booking API Documentation',
      customfavIcon: `http://${configApp.appUrl}:${configApp.port}/images/asd.ico`,
    });
  }
}

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);

  app.useGlobalPipes(new ValidationPipe({ whitelist: true }));

  app.enableCors();
  app.useStaticAssets(pathLib.join(__dirname, '..', 'assets'));
  const docUsers = {};
  docUsers[configDoc.username] = configDoc.password;
  app.use(
    // Paths you want to protect with basic auth
    '/docs*',
    basicAuth({
      challenge: true,
      users: docUsers,
    })
  );
  await docApi(app);
  const port = parseInt(process.env.PORT, 10) || 3000;
  await app.listen(port);
}

bootstrap();

How can I resolve this, or did I enter wrong path to enter swagger? Please help

2

There are 2 best solutions below

0
Alfred Doh-Nani On

Here's a snippet of my setup in main.ts:

 const config = new DocumentBuilder()
      .setTitle('API DOCS')
      .setDescription('REST API Documentation')
      .setVersion('1.0')
      .addBearerAuth()
      .build();
    const document = SwaggerModule.createDocument(app, config);
    SwaggerModule.setup('api', app, document, {
      jsonDocumentUrl: 'api/json-spec',
      yamlDocumentUrl: 'api/yaml-spec',
      customSiteTitle: 'API DOCS',
    });

where app is const app = await NestFactory.create<NestExpressApplication>(AppModule); in your case.

I can then access the swagger docs at http:localhost:3000/api, the JSON spec at http:localhost:3000/api/json-spec, and the YAML spec at http:localhost:3000/api/yaml-spec.

I'm unsure why you needed to abstract your implementation into a function.

1
berat On

You can use that;

const config = new DocumentBuilder() .setTitle(configurations().open_api_title + ' ('+ configurations().PROJECT_ENV +')') .setVersion(configurations().open_api_version) .setDescription(configurations().open_api_description) .setExternalDoc("openapi.json",/${configurations().swagger_path}-json) .addSecurity("bearer", { type: "http", scheme: "bearer", }) .build();