@nestjs/core#NestFactory TypeScript Examples

The following examples show how to use @nestjs/core#NestFactory. 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 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 #2
Source File: main.ts    From nr-apm-stack with Apache License 2.0 6 votes vote down vote up
/**
 * Bootstrap the nest application for localhost testing.
 */
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.getHttpAdapter().getInstance().set('json spaces', 2);
  app.use(json({limit: '50mb'}));
  await app.listen(3000);
}
Example #3
Source File: gateway.spec.ts    From nestjs-mercurius with MIT License 6 votes vote down vote up
graphqlSuite.before.each(async (ctx) => {
  const userApp = await NestFactory.create(UserModule, new FastifyAdapter());
  const postApp = await NestFactory.create(PostModule, new FastifyAdapter());

  await Promise.all([userApp.listen(3001), postApp.listen(3002)]);

  ctx.services = [userApp, postApp];

  await sleep(500);

  const module = await Test.createTestingModule({
    imports: [GatewayModule],
  }).compile();

  const app = module.createNestApplication<NestFastifyApplication>(
    new FastifyAdapter(),
  );
  await app.init();
  ctx.app = app;
  ctx.mercuriusClient = createTestClient(module);
});
Example #4
Source File: main.ts    From nestjs-api-example with MIT License 6 votes vote down vote up
async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  const configService = app.get<ConfigService>(ConfigService);

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

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

  setupSwagger(app);

  const port = configService.get('APP_PORT');
  await app.listen(port);

  console.info(`Server listening on port ${port}`);
}
Example #5
Source File: index.ts    From typegraphql-nestjs with MIT License 6 votes vote down vote up
async function bootstrap() {
  const firstApp = await NestFactory.create<NestFastifyApplication>(
    FirstAppModule,
    new FastifyAdapter(),
  );
  const secondApp = await NestFactory.create<NestFastifyApplication>(
    SecondAppModule,
    new FastifyAdapter(),
  );

  await firstApp.listen(3001);
  await secondApp.listen(3002);
}
Example #6
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 #7
Source File: default-scan-process.ts    From barista with Apache License 2.0 6 votes vote down vote up
// tslint:enable:ordered-imports

/**
 * The default scan process.
 * @param job A BullQueue Job instance
 * @param cb A callback function to be executed upon completion.
 */
export default function(job: Job, cb: DoneCallback) {
  async function bootstrap() {
    const logger = new Logger('DefaultScanProcess');
    const app = await NestFactory.createApplicationContext(DefaultScanModule);
    const workerService = app.get(DefaultScanWorkerService);
    logger.log('Starting DefaultScanWorker');
    await workerService.scan(job, cb);
    logger.log('Finished DefaultScanWorker');
    await app.close();
    logger.log('App Closed...');
  }

  bootstrap();
}
Example #8
Source File: runner.ts    From nestjs-geteventstore with MIT License 6 votes vote down vote up
async function bootstrap() {
  const app: INestApplication = await NestFactory.create(
    EventStoreHeroesModule,
    {
      logger: ['log', 'error', 'warn', 'debug', 'verbose'],
    },
  );

  app.useGlobalFilters(new AllExceptionFilter());
  await app.listen(3000, () => {
    console.log('Application is listening on port 3000.');
  });
}
Example #9
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 #10
Source File: main.ts    From whispr with MIT License 6 votes vote down vote up
async function bootstrap() {
  const adapter = new FastifyAdapter({ logger: configService.getLogLevel() });
  const fastifyInstance = adapter.getInstance();
  fastifyInstance.addContentTypeParser('multipart', (request, done) => {
    request.isMultipart = true;
    done();
  });

  fastifyInstance.addHook('preValidation', async (request: any, reply) => {
    if (!request.raw.isMultipart) {
      return;
    }
    request.body = await processRequest(request.raw, reply.raw);
  });
  const app = await NestFactory.create<NestFastifyApplication>(AppModule, adapter);
  app.enableCors();
  app.register(Fastify);
  if (process.env.DEBUG_HTTP_HEADERS === 'true') {
    app.use(logger);
  }
  await app.listen(3000, '0.0.0.0');
}
Example #11
Source File: main.ts    From svvs with MIT License 6 votes vote down vote up
/**
 * Bootstrap backend-api app
 */
async function bootstrap() {
  const app = await NestFactory.create(AppModule)
  const globalPrefix = 'api'
  app.setGlobalPrefix(globalPrefix)
  const port = process.env.API_PORT || 3333
  await app.listen(port, () => {
    Logger.log('Listening at http://localhost:' + port + '/' + globalPrefix)
  })
}
Example #12
Source File: DesktopAPI.ts    From rewind with MIT License 6 votes vote down vote up
export async function setupBootstrap({ userDataPath, logDirectory }: SetupBootstrapSettings) {
  const rewindCfgPath = getRewindCfgPath(userDataPath);
  const rewindCfgProvider = {
    provide: REWIND_CFG_PATH,
    useValue: rewindCfgPath,
  };

  @Module({
    providers: [rewindCfgProvider, DesktopConfigService],
    controllers: [DesktopConfigController, SetupStatusController],
  })
  class SetupModule {}

  const app = await NestFactory.create<NestExpressApplication>(SetupModule, { logger: createLogger(logDirectory) });
  app.setGlobalPrefix(globalPrefix);
  app.enableCors();

  await app.listen(port, listenCallback);
  return app;
}
Example #13
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 #14
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 #15
Source File: main.ts    From remix-hexagonal-architecture with MIT License 6 votes vote down vote up
async function bootstrap() {
  const app = await NestFactory.create(
    ApplicationModule.register({
      session,
      remixHandlerPath: path.join(__dirname, "../../build"),
    }),
    {
      bodyParser: false,
    }
  );

  return app.listen(process.env.PORT ?? 3000);
}
Example #16
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 #17
Source File: index.ts    From test with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
bootstrap = async () => {
  const app = await NestFactory.createMicroservice(ServiceModule, serverOptions)

  useContainer(app.select(ServiceModule), {
    fallback: true,
    fallbackOnErrors: true,
  })

  await app.listenAsync()

  if (module.hot) {
    module.hot.accept()
    module.hot.dispose(() => app.close())
  }
}
Example #18
Source File: main.ts    From nestjs-rest-microservices with MIT License 6 votes vote down vote up
async function bootstrap() {
  const app = await NestFactory.create(AppModule)

  app.useLogger(app.get(Logger))
  app.enableCors({
    origin: '*'
  })

  return app.listen(process.env.PORT)
}
Example #19
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 #20
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 #21
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 #22
Source File: main.ts    From nestjs-jaeger-tracing with MIT License 6 votes vote down vote up
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.connectMicroservice<MicroserviceOptions>({
    transport: Transport.TCP,
  });
  await app.startAllMicroservicesAsync();
  await app.listen(3000);
  const url = await app.getUrl();
  logger.verbose(`Nest application is listening on ${url}`);
}
Example #23
Source File: seeder.ts    From nestjs-seeder with MIT License 6 votes vote down vote up
async function bootstrap(options: SeederModuleOptions) {
  const app = await NestFactory.createApplicationContext(
    SeederModule.register(options)
  );
  const seedersService = app.get(SeederService);
  await seedersService.run();

  await app.close();
}
Example #24
Source File: main.ts    From erda-ui with GNU Affero General Public License v3.0 6 votes vote down vote up
async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    httpsOptions: isProd ? undefined : getHttpsOptions(),
  });
  app.use(helmet({ contentSecurityPolicy: false, referrerPolicy: false }));
  app.useGlobalFilters(new AllExceptionsFilter());
  app.useGlobalFilters(new NotFoundExceptionFilter());
  if (isProd) {
    app.use(compression()); // gzip
  }
  app.use(guardMiddleware); // must create global guard middleware here, otherwise the proxy middleware will ignore the guard
  const wsProxy = createProxyService(app);

  const server = await app.listen(isProd ? 80 : SCHEDULER_PORT);
  server.on('upgrade', wsProxy.upgrade);

  if (isProd) {
    logger.info('erda ui server started at port 80');
  } else {
    logger.info(`server started at ${SCHEDULER_URL}:${SCHEDULER_PORT || 3000}`);
  }
}
Example #25
Source File: main.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
async function bootstrap() {
  const { kafka, healthcheck } = configuration();

  const healthCheckApp = await NestFactory.create(HealthcheckModule, { cors: true });
  logger.log(`HelathCheckApp successfully run on the ${healthcheck.port} ?`);
  await healthCheckApp.listen(healthcheck.port);

  const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, {
    transport: Transport.KAFKA,
    options: {
      client: {
        clientId: kafka.clientId,
        brokers: kafka.brokers,
        sasl: {
          mechanism: 'plain',
          username: kafka.sasl.username,
          password: kafka.sasl.password,
        },
      },
      consumer: {
        groupId: kafka.groupId,
      },
    },
  });
  await waitReady();
  changeStatus('database');
  await app.listen();
  changeStatus('kafka');
}
Example #26
Source File: main.ts    From nestjs-rest-sample with GNU General Public License v3.0 6 votes vote down vote up
async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // enable shutdown hooks explicitly.
  app.enableShutdownHooks();

  app.useGlobalPipes(new ValidationPipe());
  app.enableCors();
  //app.useLogger();
  await app.listen(3000);
}
Example #27
Source File: index.ts    From aws-nestjs-starter with The Unlicense 6 votes vote down vote up
bootstrapServer = async (): Promise<Handler> => {
  const expressApp = express();
  const app = await NestFactory.create(
    AppModule,
    new ExpressAdapter(expressApp),
  );
  app.useGlobalPipes(new ValidationPipe({ forbidUnknownValues: true }));
  app.enableCors();
  await app.init();
  return serverlessExpress({
    app: expressApp,
  });
}
Example #28
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 #29
Source File: main.ts    From life-helper-backend with MIT License 6 votes vote down vote up
async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule, { cors: true })

  // 添加全局自动验证管道
  app.useGlobalPipes(
    new ValidationPipe({
      /** 负载对象自动转换 */
      transform: true,
      transformOptions: { enableImplicitConversion: true },

      /** 自动过滤未知参数 */
      whitelist: true,
    })
  )

  // 关闭 `ETag` 响应头
  app.set('etag', false)

  // 设置反向代理,获取客户端 IP 地址
  app.set('trust proxy', PROXY_NUMBER)

  // 关闭 `X-Powered-By` 响应头
  app.set('x-powered-by', false)

  // 挂载 Swagger 插件
  setupSwagger(app)

  await app.listen(PORT, '0.0.0.0')
}