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
Here's a snippet of my setup in main.ts:
where
appisconst app = await NestFactory.create<NestExpressApplication>(AppModule);in your case.I can then access the swagger docs at
http:localhost:3000/api, theJSON specathttp:localhost:3000/api/json-spec, and the YAML spec athttp:localhost:3000/api/yaml-spec.I'm unsure why you needed to abstract your implementation into a function.