@nestjs/swagger#SwaggerModule TypeScript Examples

The following examples show how to use @nestjs/swagger#SwaggerModule. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: main.ts    From mamori-i-japan-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    logger: false,
  })

  app.useLogger(new AppLogger())
  app.use(RequestIdMiddleware)
  app.enableCors()

  const configService = app.get(ConfigService)
  const backendAppPort = configService.get('BACKEND_APP_PORT')

  const options = new DocumentBuilder()
    .setTitle('mamori-i-japan-api')
    .setDescription('Swagger UI for mamori-i-japan-api API')
    .setVersion('1.0')
    .addBearerAuth()
    .build()
  const document = SwaggerModule.createDocument(app, options)
  SwaggerModule.setup('swagger', app, document)

  await app.listen(backendAppPort)
}
Example #2
Source File: main.ts    From nestjs-file-streaming with MIT License 6 votes vote down vote up
async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter(),
  )

  app.enableShutdownHooks()

  app.register(fastifyMulipart)

  const options = new DocumentBuilder()
    .setTitle('NestJS Fastify Streaming Server')
    .setDescription('Stream files to and from a MongoDB.')
    .setVersion(version)
    .addTag('File')
    .build()
  const document = SwaggerModule.createDocument(app, options)
  SwaggerModule.setup('api', app, document)

  await app.listen(3101, '0.0.0.0', () => {
    console.log('Server listening at http://0.0.0.0:' + 3101 + '/api/')
  })
}
Example #3
Source File: main.ts    From edu-server with MIT License 6 votes vote down vote up
async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // setup swagger-ui
  const document = SwaggerModule.createDocument(app, swaggerConfig);
  SwaggerModule.setup('api', app, document, customOptions);

  // Firebase Initialisation
  admin.initializeApp(firebaseAccountCredentials);

  app.enableCors();
  app.use(helmet());

  // The Cors handling middleware
  app.use((req: Request, res: Response, next: NextFunction) => {
    res.set('Access-Control-Allow-Origin', '*');
    res.set('Access-Control-Allow-Headers', '*');
    res.set('Access-Control-Allow-Methods', '*');
    if (req.method === 'OPTIONS') {
      res.status(200).end();
      return;
    }
    next();
  });
  app.useGlobalPipes(new ValidationPipe());

  const PORT = process.env.PORT || 5000;
  await app.listen(PORT);
  console.log('App is listening on port:', PORT);
}
Example #4
Source File: main.ts    From pandaid with MIT License 6 votes vote down vote up
async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    logger: new PinoLoggerService(logger)
  })
  app.setGlobalPrefix('api')
  app.enableCors() // TODO remove for production
  app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true }))

  const options = new DocumentBuilder()
    .setTitle('PandAid')
    .setDescription('The PandAid API description')
    .setVersion('1.0')
    .addBearerAuth()
    .build()

  const document = SwaggerModule.createDocument(app, options)
  SwaggerModule.setup('swagger', app, document)

  const port = process.env.PORT || 3001
  logger.info(`Listening on port ${port}`)
  await app.listen(port)
}
Example #5
Source File: main.ts    From nestjs-crud-prisma with MIT License 6 votes vote down vote up
(async () => {
  const app = await NestFactory.create<NestExpressApplication>(AppModule, {
    bodyParser: true
  });
  app.setBaseViewsDir(path.resolve(rootPath, 'views'));
  app.setViewEngine('ejs');
  app.useGlobalPipes(new ValidationPipe());
  app.useStaticAssets(path.resolve(rootPath, 'public'));
  app.useGlobalFilters(new HttpExceptionFilter());
  if (env.SWAGGER === '1') {
    const options = new DocumentBuilder()
      .setTitle(pkg.name)
      .setDescription(pkg.description)
      .setVersion('1.0')
      .build();
    const document = SwaggerModule.createDocument(app, options);
    SwaggerModule.setup('api', app, document);
  }
  if (env.CORS === '1') app.enableCors();
  await app
    .listen(await getPort({ port: Number(env.PORT || 3000) }))
    .catch(logger.error);
  if (module.hot) {
    module.hot.accept();
    module.hot.dispose(() => app.close());
  }
})();
Example #6
Source File: main.ts    From aqualink-app with MIT License 6 votes vote down vote up
async function bootstrap() {
  if (Object.values(serviceAccount).every((value) => !!value)) {
    admin.initializeApp({
      credential: admin.credential.cert(serviceAccount),
    });
  } else {
    Logger.warn('Firebase environments not provided', 'MAIN');
  }

  const app = await NestFactory.create(AppModule);

  const { config, documentOptions, customOptions } =
    configService.getSwaggerConfig();
  const document = SwaggerModule.createDocument(app, config, documentOptions);
  SwaggerModule.setup('api/docs', app, document, customOptions);

  app.enableCors();
  app.setGlobalPrefix('api');
  app.useGlobalPipes(
    new GlobalValidationPipe({ transform: true, skipTransformIds: ['appId'] }),
  );
  app.useGlobalFilters(
    new HttpExceptionFilter(),
    new UnauthorizedExceptionFilter(),
  );
  app.use(apiLoggerMiddleware);
  // eslint-disable-next-line react-hooks/rules-of-hooks
  useContainer(app.select(AppModule), { fallbackOnErrors: true });
  await app.listen(8080);
  // eslint-disable-next-line no-console
  console.log(`App listening on port 8080`);
}
Example #7
Source File: main.ts    From amplication with Apache License 2.0 6 votes vote down vote up
async function main() {
  const app = await NestFactory.create(AppModule, { cors: true });

  app.setGlobalPrefix("api");
  app.useGlobalPipes(
    new ValidationPipe({
      transform: true,
    })
  );

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

  /** check if there is Public decorator for each path (action) and its method (findMany / findOne) on each controller */
  Object.values((document as OpenAPIObject).paths).forEach((path: any) => {
    Object.values(path).forEach((method: any) => {
      if (
        Array.isArray(method.security) &&
        method.security.includes("isPublic")
      ) {
        method.security = [];
      }
    });
  });

  SwaggerModule.setup(swaggerPath, app, document, swaggerSetupOptions);

  void app.listen(PORT);

  return app;
}
Example #8
Source File: main.ts    From nest-js-quiz-manager with MIT License 6 votes vote down vote up
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableCors();

  const config = new DocumentBuilder()
    .addBearerAuth()
    .setTitle('Quiz manager API')
    .setDescription('Quiz manager API description')
    .setVersion('1.0')
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, document);

  await app.listen(process.env.PORT || 3000);
}
Example #9
Source File: main.ts    From 42_checkIn with GNU General Public License v3.0 6 votes vote down vote up
async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.use(cookieParser());
  app.use(requestIp.mw());
  app.enableCors({
    origin: 'https://cluster.42seoul.io',
    credentials: true,
  });
  app.useGlobalInterceptors(
    new LoggingInterceptor(new MyLogger(new ConfigService())),
  );
  const config = new DocumentBuilder()
    .setTitle('42CheckIn')
    .setDescription('42CheckIn Open API Swagger')
    .setVersion('1.0')
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, document);
  app.useLogger(new MyLogger(new ConfigService()));
  await app.listen(3000);
}
Example #10
Source File: swagger.plugin.ts    From life-helper-backend with MIT License 6 votes vote down vote up
/**
 * 装载 `Swagger`
 *
 * @param app Application 实例
 */
export function setupSwagger(app: INestApplication): void {
  const title = '「我的个人助手」项目 API 文档'
  const description = '「我的个人助手」项目 API 文档,'
  const version = '1.0'

  const config = new DocumentBuilder().setTitle(title).setDescription(description).setVersion(version).build()
  const document = SwaggerModule.createDocument(app, config)

  SwaggerModule.setup('docs', app, document)
}
Example #11
Source File: main.ts    From domain-driven-hexagon with MIT License 6 votes vote down vote up
async function bootstrap(): Promise<void> {
  const app = await NestFactory.create(AppModule);

  const options = new DocumentBuilder().build();

  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('docs', app, document);

  app.useGlobalPipes(new ValidationPipe());

  app.useGlobalInterceptors(new ExceptionInterceptor());

  app.enableShutdownHooks();

  await app.listen(3000);
}
Example #12
Source File: _main.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  const configService = app.get(ConfigService);

  app.useGlobalPipes(new ValidationPipe());
  app.useGlobalFilters(new AllExceptionsFilter());

  const port = configService.get<number>('SERVER_PORT') || 3000;

  const options = new DocumentBuilder()
    .setTitle('Api v1')
    .setDescription('The boilerplate API for nestjs devs')
    .setVersion('1.0')
    .addBearerAuth({ in: 'header', type: 'http' })
    .build();
  const document = SwaggerModule.createDocument(app, options);

  SwaggerModule.setup('api', app, document);

  await app.listen(port, async () => {
    console.log(`The server is running on ${port} port: http://localhost:${port}/api`);
  });
}
Example #13
Source File: main.ts    From coronatest with GNU Affero General Public License v3.0 6 votes vote down vote up
async function bootstrap() {
    const app = await NestFactory.create<NestExpressApplication>(AppModule);

    const options = new DocumentBuilder()
        .setTitle('Coronatest')
        .setDescription('Coronatest API')
        .setVersion('1.0')
        .addBearerAuth()
        .build();
    const document = SwaggerModule.createDocument(app, options);
    SwaggerModule.setup('docs', app, document);

    app.disable('x-powered-by');
    app.useGlobalPipes(new ValidationPipe({ whitelist: true }));
    app.enableCors({
        origin: true,
        credentials: true
    });

    app.setGlobalPrefix('api');

    await app.listen(3000);
}
Example #14
Source File: lambda-swagger.ts    From mamori-i-japan-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
bootstrapServer = async (): Promise<Server> => {
  const expressApp = express()
  const adapter = new ExpressAdapter(expressApp)

  const app = await NestFactory.create(AppModule, adapter, {
    logger: false,
  })
  app.useLogger(new AppLogger())

  app.use(eventContext())
  app.enableCors()

  const options = new DocumentBuilder()
    .setTitle('mamori-i-japan-api')
    .setDescription('Swagger UI for mamori-i-japan-api API')
    .setVersion('1.0')
    .addBearerAuth()
    .build()
  const document = SwaggerModule.createDocument(app, options)
  SwaggerModule.setup('swagger', app, document)

  await app.init()
  return createServer(expressApp)
}
Example #15
Source File: main.ts    From nestjs-starter-rest-api with MIT License 6 votes vote down vote up
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.setGlobalPrefix('api/v1');

  app.useGlobalPipes(new ValidationPipe(VALIDATION_PIPE_OPTIONS));
  app.use(RequestIdMiddleware);
  app.enableCors();

  /** Swagger configuration*/
  const options = new DocumentBuilder()
    .setTitle('Nestjs API starter')
    .setDescription('Nestjs API description')
    .setVersion('1.0')
    .addBearerAuth()
    .build();

  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('swagger', app, document);

  const configService = app.get(ConfigService);
  const port = configService.get<number>('port');
  await app.listen(port);
}
Example #16
Source File: swagger.ts    From bank-server with MIT License 6 votes vote down vote up
export function setupSwagger(app: INestApplication): void {
  const options = new DocumentBuilder()
    .setTitle('API')
    .setVersion('2.0.0')
    .addBearerAuth()
    .build();

  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('documentation', app, document);
}
Example #17
Source File: _mongodb-main.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  const configService = app.get(ConfigService);

  app.useGlobalPipes(new ValidationPipe());
  app.useGlobalFilters(new AllExceptionsFilter());

  app.use(
    session({
      secret: configService.get<string>('PASSPORT_SESSION_SECRET') as string,
      resave: false,
      saveUninitialized: false,
      store: new MongoDBStore({
        uri: configService.get<string>('MONGODB_URL'),
        collection: 'sessions',
      }),
    }),
  );

  app.use(passport.initialize());
  app.use(passport.session());

  const options = new DocumentBuilder()
    .setTitle('Api v1')
    .setDescription('The boilerplate API for nestjs devs')
    .setVersion('1.0')
    .addCookieAuth('connect.sid')
    .build();
  const document = SwaggerModule.createDocument(app, options);

  SwaggerModule.setup('api', app, document);

  const port = configService.get<number>('SERVER_PORT') || 3000;

  await app.listen(port, async () => {
    console.log(`The server is running on ${port} port: http://localhost:${port}/api`);
  });
}
Example #18
Source File: _main.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.useGlobalPipes(new ValidationPipe());
  app.useGlobalFilters(new AllExceptionsFilter());

  const configService = app.get(ConfigService);
  const port = configService.get<number>('SERVER_POR') || 3000;

  const options = new DocumentBuilder()
    .setTitle('Api v1')
    .setDescription('The boilerplate API for nestjs devs')
    .setVersion('1.0')
    .addBearerAuth({ in: 'header', type: 'http' })
    .build();
  const document = SwaggerModule.createDocument(app, options);

  SwaggerModule.setup('api', app, document);

  await app.listen(port, async () => {
    console.log(`The server is running on ${port} port: http://localhost:${port}/api`);
  });
}
Example #19
Source File: swagger.ts    From MyAPI with MIT License 6 votes vote down vote up
export function setupSwagger (app: INestApplication): void {
  const url = process.env.NODE_ENV === PROD_ENV ? 'https' : 'http'
  const options = new DocumentBuilder()
    .setTitle('MyAPI')
    .setDescription('A template to create awesome APIs easily ⚡️')
    .setVersion('1.0')
    .addTag('Endpoints')
    .setContact('Juan David Nicholls', 'https://github.com/proyecto26/MyAPI', '[email protected]')
    .addBearerAuth()
    .addServer(`${url}://`)
    .build()
  const document = SwaggerModule.createDocument(app, options)
  SwaggerModule.setup('api', app, document)
}
Example #20
Source File: ServerApplication.ts    From typescript-clean-architecture with MIT License 6 votes vote down vote up
private buildAPIDocumentation(app: NestExpressApplication): void {
    const title: string = 'IPoster';
    const description: string = 'IPoster API documentation';
    const version: string = '1.0.0';
    
    const options: Omit<OpenAPIObject, 'paths'> = new DocumentBuilder()
      .setTitle(title)
      .setDescription(description)
      .setVersion(version)
      .addBearerAuth({ type: 'apiKey', in: 'header', name: ApiServerConfig.ACCESS_TOKEN_HEADER })
      .build();
    
    const document: OpenAPIObject = SwaggerModule.createDocument(app, options);
    
    SwaggerModule.setup('documentation', app, document);
  }
Example #21
Source File: main.ts    From radiopanel with GNU General Public License v3.0 6 votes vote down vote up
async function bootstrap() {
	const app = await NestFactory.create(AppModule);

	app.use(helmet());
	app.use(sessionMiddleware)
	app.use(passport.initialize())
	app.use(passport.session())
	
	passport.serializeUser((user, done) => done(null, user));
	passport.deserializeUser((user, done) => done(null, user));

	app.useWebSocketAdapter(new RedisIoAdapter(app));
	app.useWebSocketAdapter(new SessionAdapter(app))
	app.useGlobalInterceptors(new TransformInterceptor());
	app.setGlobalPrefix('api/v1');
	app.enableCors({
		exposedHeaders: ['x-tenant'],
	});

	const options = new DocumentBuilder()
		.setTitle('RadioPanel')
		.setDescription('The RadioPanel API documentation, baseURL: https://api.radiopanel.co')
		.setVersion('1.0')
		.addBasicAuth()
		.build();
	const document = SwaggerModule.createDocument(app, options);
	SwaggerModule.setup('api', app, document);

	await app.listen(Number(process.env.PORT));
}
Example #22
Source File: main.ts    From pknote-backend with GNU General Public License v3.0 6 votes vote down vote up
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const config = new DocumentBuilder()
    .setTitle('PkNote Swagger')
    .setDescription('PkNote backend API')
    .setVersion('1.0')
    .addTag('beta')
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, document);
  await app.listen(3000);
}
Example #23
Source File: _mongodb-main.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  const configService = app.get(ConfigService);

  app.useGlobalPipes(new ValidationPipe());
  app.useGlobalFilters(new AllExceptionsFilter());

  app.use(
    session({
      secret: configService.get<string>('PASSPORT_SESSION_SECRET') as string,
      resave: false,
      saveUninitialized: false,
      store: new MongoDBStore({
        uri: configService.get<string>('MONGODB_URL'),
        collection: 'sessions',
      }),
    }),
  );

  app.use(passport.initialize());
  app.use(passport.session());

  const options = new DocumentBuilder()
    .setTitle('Api v1')
    .setDescription('The boilerplate API for nestjs devs')
    .setVersion('1.0')
    .addCookieAuth('connect.sid')
    .build();
  const document = SwaggerModule.createDocument(app, options);

  SwaggerModule.setup('api', app, document);

  const port = configService.get<number>('SERVER_POR') || 3000;

  await app.listen(port, async () => {
    console.log(`The server is running on ${port} port: http://localhost:${port}/api`);
  });
}
Example #24
Source File: _main.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.useGlobalPipes(new ValidationPipe({
    exceptionFactory: (errors: ValidationError[]) => new ValidationExceptions(errors),
  }));
  app.useGlobalFilters(new AllExceptionsFilter());

  const configService = app.get(ConfigService);
  const port = configService.get<number>('SERVER_POR') || 3000;

  const options = new DocumentBuilder()
    .setTitle('Api v1')
    .setDescription('The boilerplate API for nestjs devs')
    .setVersion('1.0')
    .addBearerAuth({ in: 'header', type: 'http' })
    .build();
  const document = SwaggerModule.createDocument(app, options);

  SwaggerModule.setup('api', app, document);

  await app.listen(port, async () => {
    console.log(`The server is running on ${port} port: http://localhost:${port}/api`);
  });
}
Example #25
Source File: swagger.ts    From nestjs-api-example with MIT License 6 votes vote down vote up
/**
 * Swagger 세팅
 *
 * @param {INestApplication} app
 */
export function setupSwagger(app: INestApplication): void {
  const options = new DocumentBuilder()
    .setTitle('NestJS Study API Docs')
    .setDescription('NestJS Study API description')
    .setVersion('1.0.0')
    .build();

  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('api-docs', app, document);
}
Example #26
Source File: index.ts    From nestjs-starter with MIT License 6 votes vote down vote up
setupApiDocs = (app: INestApplication) => {
  const options = new DocumentBuilder()
    .setTitle(SWAGGER_API_NAME)
    .setDescription(SWAGGER_API_DESCRIPTION)
    .setVersion(SWAGGER_API_CURRENT_VERSION)
    .build();
  const document = SwaggerModule.createDocument(app, options);

  SwaggerModule.setup(SWAGGER_API_ROOT, app, document);
}
Example #27
Source File: main.ts    From nest_transact with MIT License 5 votes vote down vote up
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalFilters(new ExampleExceptionFilter());
  const options = new DocumentBuilder().setTitle('Nest Transact Example').setDescription('Showcase with transactions').setVersion('1.0').build();
  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('api', app, document);
  await app.listen(3000);
}
Example #28
Source File: main.ts    From ironfish-api with Mozilla Public License 2.0 5 votes vote down vote up
async function bootstrap(): Promise<void> {
  const server = express();
  const app = await NestFactory.create<NestExpressApplication>(
    AppModule,
    new ExpressAdapter(server),
  );
  const config = app.get(ApiConfigService);
  const logger = app.get(LoggerService);

  const defaultOrigins = [
    config.get<string>('BLOCK_EXPLORER_URL'),
    config.get<string>('INCENTIVIZED_TESTNET_URL'),
  ];
  const enabledOrigins = config.isStaging()
    ? [
        ...defaultOrigins,
        /localhost/,
        /block-explorer.*\.vercel\.app/,
        /website-testnet.*\.vercel\.app/,
      ]
    : defaultOrigins;

  app.enableCors({
    origin: enabledOrigins,
    methods: 'GET, POST, PUT, OPTIONS',
    allowedHeaders: ['Content-Type', 'Accept', 'Authorization'],
    credentials: true,
  });

  app.use(compression());
  app.use(helmet());
  app.use(json({ limit: '10mb' }));

  const swaggerConfig = new DocumentBuilder()
    .setTitle('Iron Fish API')
    .setDescription('The Rest API to enable public access to Iron Fish data')
    .setVersion('')
    .build();
  const document = SwaggerModule.createDocument(app, swaggerConfig);
  SwaggerModule.setup('docs', app, document, {
    customSiteTitle: 'Iron Fish API Documentation',
  });

  await app.init();

  const port = config.get<number>('PORT');
  logger.info(`Starting API on PORT ${port}`);
  const httpServer = http.createServer(server).listen(port);

  if (module.hot) {
    module.hot.accept();
    module.hot.dispose(() => {
      httpServer.close();
      void app.close();
    });
  }
}
Example #29
Source File: main.ts    From nestjs-starter with MIT License 5 votes vote down vote up
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const logger = new Logger('Bootstrap');
  const configService = app.get(ConfigService);

  // Swagger
  const options = new DocumentBuilder()
    .addBearerAuth()
    .setTitle('Nest Starter Boilerplate')
    .setDescription('Nest collection of tools and authentication ready to use.')
    .setVersion('1.0')
    .build();
  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('', app, document);

  // Environments
  const port = configService.get<number>(CONFIG_SERVER_PORT);
  const environment = configService.get<string>(NODE_ENV);

  // Interceptors and validators
  app.useGlobalInterceptors(new TransformInterceptor());
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      forbidUnknownValues: true,
      skipMissingProperties: false,
      transform: true,
    }),
  );

  // Security setup
  app.use(helmet());
  app.enableCors();
  app.use(
    rateLimit({
      windowMs: 15 * 60 * 1000, // 15 minutes
      max: 100, // limit each IP to 100 requests per windowMs
    }),
  );

  // compression
  app.use(compression());

  await app.listen(port);
  logger.log(`Application is running in ${environment.toUpperCase()} on: ${await app.getUrl()}`);
}