@nestjs/platform-express#NestExpressApplication TypeScript Examples

The following examples show how to use @nestjs/platform-express#NestExpressApplication. 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 nestjs-starter with MIT License 6 votes vote down vote up
async function bootstrap(): Promise<void> {
  const app = await NestFactory.create<NestExpressApplication>(AppModule, {
    logger: WinstonModule.createLogger(loggerConfig),
  });
  const logger = app.get(WINSTON_MODULE_NEST_PROVIDER);
  const configService = app.get(ConfigService);

  app.enableCors({
    credentials: true,
    origin: configService.get('CLIENT_URL'),
  });
  app.enableShutdownHooks();
  app.get(AppModule).subscribeToShutdown(() => app.close());

  app.use(cookieParser(configService.get('COOKIE_SECRET')));
  app.use(loggerMiddleware);
  app.useGlobalFilters(new HttpExceptionFilter());
  app.useGlobalPipes(
    new CustomValidationPipe({
      forbidNonWhitelisted: true,
      forbidUnknownValues: true,
      whitelist: true,
    }),
  );
  setupApiDocs(app);

  await app.listen(configService.get('PORT')).then(() => {
    logger.log(`Server is running on port ${configService.get('PORT')}`);
  });
}
Example #2
Source File: TestServer.ts    From typescript-clean-architecture with MIT License 6 votes vote down vote up
public static async new(): Promise<TestServer> {
    const testingModule: TestingModule = await Test
      .createTestingModule({imports: [RootModule]})
      .compile();
  
    initializeTransactionalContext();
    patchTypeORMRepositoryWithBaseRepository();
    
    const dbConnection: Connection = testingModule.get(Connection);
    const serverApplication: NestExpressApplication = testingModule.createNestApplication();
    
    return new TestServer(serverApplication, dbConnection, testingModule);
  }
Example #3
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 #4
Source File: jestSetupAfterEnv.ts    From domain-driven-hexagon with MIT License 6 votes vote down vote up
public static async new(
    testingModuleBuilder: TestingModuleBuilder,
  ): Promise<TestServer> {
    const testingModule: TestingModule = await testingModuleBuilder.compile();

    const serverApplication: NestExpressApplication = testingModule.createNestApplication();
    await serverApplication.init();

    return new TestServer(serverApplication, testingModule);
  }
Example #5
Source File: main.ts    From MyAPI with MIT License 6 votes vote down vote up
async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule, {
    logger: process.env.NODE_ENV === PROD_ENV ? createLogger() : ['error', 'warn', 'debug']
  })

  // BASIC CONFIGURATION
  app.useStaticAssets(join(__dirname, 'public'))
  app.setBaseViewsDir(join(__dirname, 'views'))
  app.setViewEngine('ejs')

  // PARSE REQUESTS
  app.use(urlencoded({ extended: true }))
  app.use(json({
    limit: '10mb'
  }))
  app.useGlobalPipes(
    new ValidationPipe({
      transform: true,
      whitelist: true,
      forbidNonWhitelisted: true
    })
  )

  // SECURITY
  setupSecurity(app)

  // OPEN API
  setupSwagger(app)

  // Register the proxy’s IP address (load balancer or reverse proxy)
  app.set('trust proxy', function (ip: string) {
    if (ip === '127.0.0.1') return true // trusted IPs
    else return false
  })

  await app.listen(process.env.PORT || 3000)
}
Example #6
Source File: main.ts    From bank-server with MIT License 6 votes vote down vote up
async function bootstrap(): Promise<void> {
  initializeTransactionalContext();
  patchTypeORMRepositoryWithBaseRepository();

  const app = await NestFactory.create<NestExpressApplication>(
    AppModule,
    new ExpressAdapter(),
    { cors: true },
  );

  app.enable('trust proxy');
  app.use(helmet());
  app.use(RateLimit({ windowMs: 15 * 60 * 1000, max: 200 }));
  app.use(compression());
  app.use(morgan('combined'));
  app.setGlobalPrefix('bank');

  const reflector = app.get(Reflector);

  app.useGlobalInterceptors(new ClassSerializerInterceptor(reflector));
  app.useGlobalFilters(
    new HttpExceptionFilter(reflector),
    new QueryFailedFilter(reflector),
  );
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      transform: true,
      dismissDefaultMessages: true,
      validationError: { target: false },
    }),
  );

  setupSwagger(app);

  const configService = app.get(ConfigService);
  await app.listen(configService.get('PORT'));
}
Example #7
Source File: main.ts    From emutypekov with GNU General Public License v3.0 6 votes vote down vote up
async function bootstrap(logger: Logger) {
  logger.log(SystemService.Watermark);

  const app = await NestFactory.create<NestExpressApplication>(CoreModule);

  app.useGlobalInterceptors(new SystemInterceptor());
  app.useStaticAssets(join(__dirname, '..', 'web', 'static'));
  app.setBaseViewsDir(join(__dirname, '..', 'web', 'views'));
  app.setViewEngine('hbs');
  app.disable('etag');

  if (DODEBUG) {
    DebugModule.graph(app);
  }

  const common = app.select(CoreModule).get(CommonService);

  try {
    await app.listen(common.serverConfig.port, common.serverConfig.address);
    logger.log(
      `${SystemService.Server} is listening on ${common.serverConfig.address}:${common.serverConfig.port}.`,
    );
  } catch (e) {
    logger.error(e);
  }
}
Example #8
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 #9
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 #10
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 #11
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')
}
Example #12
Source File: _mysql-main.ts    From nest-js-boilerplate with MIT License 5 votes vote down vote up
async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);

  const configService = app.get(ConfigService);

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

  const viewsPath = join(__dirname, '../public/views');

  app.engine('.hbs', exphbs({
    extname: '.hbs',
    defaultLayout: 'main',
    helpers: {
      isAdmin: (role: string) => role === RolesEnum.admin,
    },
  }));
  app.set('views', viewsPath);
  app.set('view engine', '.hbs');

  app.use(
    session({
      secret: configService.get<string>('PASSPORT_SESSION_SECRET') as string,
      resave: false,
      saveUninitialized: false,
      store: new MySQLStore({
        host: configService.get<string>('MYSQL_HOST'),
        port: configService.get<number>('MYSQL_PORT'),
        user: configService.get<string>('MYSQL_ROOT_USER'),
        password: configService.get<string>('MYSQL_PASSWORD'),
        database: configService.get<string>('MYSQL_DB'),
      }),
    }),
  );

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

  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 #13
Source File: TestServer.ts    From typescript-clean-architecture with MIT License 5 votes vote down vote up
constructor(
    public readonly serverApplication: NestExpressApplication,
    public readonly dbConnection: Connection,
    public readonly testingModule: TestingModule,
  ) {}
Example #14
Source File: ServerApplication.ts    From typescript-clean-architecture with MIT License 5 votes vote down vote up
public async run(): Promise<void> {
    const app: NestExpressApplication = await NestFactory.create<NestExpressApplication>(RootModule);
    
    this.buildAPIDocumentation(app);
    this.log();
  
    await app.listen(this.port, this.host);
  }
Example #15
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 #16
Source File: DesktopAPI.ts    From rewind with MIT License 5 votes vote down vote up
/**
 * The usual bootstrap happens with the concrete knowledge of the osu! folder. Only at the first start up of the
 * application we will have to refer to boot differently.
 */
async function normalBootstrap(settings: {
  osuFolder: string;
  songsFolder: string;
  userDataPath: string;
  appResourcesPath: string;
  logDirectory: string;
}) {
  const { osuFolder, userDataPath, appResourcesPath, logDirectory, songsFolder } = settings;
  // Find out osu! folder through settings
  const rewindCfgPath = getRewindCfgPath(userDataPath);
  const skinNameResolverConfig: SkinNameResolverConfig = [
    { prefix: "osu", path: join(osuFolder, "Skins") },
    { prefix: "rewind", path: join(appResourcesPath, "Skins") },
  ];

  @Module({
    imports: [EventEmitterModule.forRoot()],
    controllers: [
      LocalReplayController,
      SkinController,
      LocalBlueprintController,
      NormalStatusController,
      DesktopConfigController,
    ],
    providers: [
      { provide: OSU_FOLDER, useValue: osuFolder },
      { provide: OSU_SONGS_FOLDER, useValue: songsFolder },
      { provide: REWIND_CFG_PATH, useValue: rewindCfgPath },
      { provide: SKIN_NAME_RESOLVER_CONFIG, useValue: skinNameResolverConfig },
      SkinNameResolver,
      SkinService,
      EventsGateway,
      ReplayWatcher,
      LocalReplayService,
      LocalBlueprintService,
      OsuDBDao,
      DesktopConfigService,
    ],
  })
  class RewindDesktopModule implements OnModuleInit {
    constructor(private moduleRef: ModuleRef) {}

    async onModuleInit(): Promise<void> {
      const [osuFolder, replayWatcher, localBlueprintService] = await Promise.all([
        this.moduleRef.resolve(OSU_FOLDER),
        this.moduleRef.resolve(ReplayWatcher),
        this.moduleRef.resolve(LocalBlueprintService),
      ]);

      const replaysFolder = join(osuFolder, "Replays");
      replayWatcher.watchForReplays(replaysFolder);

      localBlueprintService
        .getAllBlueprints()
        .then((blueprints) => Logger.log(`Loaded all ${Object.keys(blueprints).length} blueprints.`));
      // TODO: Emit and then set the status to booted
      Logger.log(`RewindDesktopModule onModuleInit finished with settings: ${JSON.stringify(settings)}`);
    }
  }

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

  app.setGlobalPrefix(globalPrefix);
  app.enableCors();

  // So that "rewind" skins are also accessible
  skinNameResolverConfig.forEach((config) => {
    app.useStaticAssets(config.path, { prefix: `/static/skins/${config.prefix}` });
  });
  app.useStaticAssets(songsFolder, { prefix: "/static/songs" });
  // app.useLogger();

  await app.listen(port, listenCallback);
}
Example #17
Source File: main.ts    From uniauth-backend with MIT License 5 votes vote down vote up
/**
 * Bootstrap application by attaching middleware and initializing auxillary services
 * @internal
 */
async function bootstrap() {
  /** set the logging levels */
  const app = await NestFactory.create<NestExpressApplication>(AppModule, {
    logger: WinstonModule.createLogger(logger.console()),
  });

  /** configuring public and views directory */
  app.useStaticAssets(join(__dirname, '../..', 'public'));
  app.setBaseViewsDir(join(__dirname, '../..', 'views'));
  hbs.registerPartials(join(__dirname, '../../views', 'partials'));

  app.setViewEngine('hbs');
  console.log(__dirname);

  /** configuring swaggerUI */
  const options = new DocumentBuilder()
    .setTitle(config.get('api.name'))
    .setDescription(config.get('api.description'))
    .setVersion(config.get('api.version'))
    .setContact('Yash Kumar Verma', 'https://yashkumarverma.github.io/', '[email protected]')
    .setLicense('MIT', 'https://opensource.org/licenses/MIT')
    .addBearerAuth({ type: 'http', scheme: 'bearer', bearerFormat: 'JWT' }, 'access-token')
    .build();

  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup(config.get('api.route'), app, document);

  /** attaching middleware */
  app.enableCors();
  //   app.use(helmet());

  /**
   * windowMs : time interval
   * max: number of requests
   *
   * this will allow max number of requests every windowMs seconds
   */
  app.use(
    rateLimit({
      windowMs: 1000 * 1,
      max: 10,
    }),
  );

  /** attach cookie parser */
  app.use(cookieParser());

  /** binding port to service */
  await app.listen(config.get('server.port'));
}
Example #18
Source File: jestSetupAfterEnv.ts    From domain-driven-hexagon with MIT License 5 votes vote down vote up
constructor(
    public readonly serverApplication: NestExpressApplication,
    public readonly testingModule: TestingModule,
  ) {}
Example #19
Source File: _redis-main.ts    From nest-js-boilerplate with MIT License 5 votes vote down vote up
async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);

  const configService = app.get(ConfigService);

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

  const viewsPath = join(__dirname, '../public/views');

  app.engine('.hbs', exphbs({
    extname: '.hbs',
    defaultLayout: 'main',
    helpers: {
      isAdmin: (role: string) => role === RolesEnum.admin,
    },
  }));
  app.set('views', viewsPath);
  app.set('view engine', '.hbs');

  app.use(
    session({
      secret: configService.get<string>('PASSPORT_SESSION_SECRET') as string,
      resave: false,
      saveUninitialized: false,
      store: new RedisStore({
        host: configService.get<string>('REDIS_HOST'),
        port: configService.get<number>('REDIS_PORT') as unknown as number,
        client: redisClient,
        ttl: 666,
      }),
    }),
  );

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

  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 #20
Source File: _mysql-main.ts    From nest-js-boilerplate with MIT License 5 votes vote down vote up
async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);

  const configService = app.get(ConfigService);

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

  const viewsPath = join(__dirname, '../public/views');

  app.engine('.hbs', exphbs({
    extname: '.hbs',
    defaultLayout: 'main',
    helpers: {
      isAdmin: (role: string) => role === RolesEnum.admin,
    },
  }));
  app.set('views', viewsPath);
  app.set('view engine', '.hbs');

  app.use(
    session({
      secret: configService.get<string>('PASSPORT_SESSION_SECRET') as string,
      resave: false,
      saveUninitialized: false,
      store: new MySQLStore({
        host: configService.get<string>('MYSQL_HOST'),
        port: configService.get<number>('MYSQL_PORT'),
        user: configService.get<string>('MYSQL_ROOT_USER'),
        password: configService.get<string>('MYSQL_PASSWORD'),
        database: configService.get<string>('MYSQL_DB'),
      }),
    }),
  );

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

  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 #21
Source File: _mongodb-main.ts    From nest-js-boilerplate with MIT License 5 votes vote down vote up
async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);

  const configService = app.get(ConfigService);

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

  const viewsPath = join(__dirname, '../public/views');

  app.engine('.hbs', exphbs({
    extname: '.hbs',
    defaultLayout: 'main',
    helpers: {
      isAdmin: (role: string) => role === RolesEnum.admin,
    },
  }));
  app.set('views', viewsPath);
  app.set('view engine', '.hbs');

  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());
  app.use(flash());

  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 #22
Source File: _redis-main.ts    From nest-js-boilerplate with MIT License 5 votes vote down vote up
async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);

  const configService = app.get(ConfigService);

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

  const viewsPath = join(__dirname, '../public/views');

  app.engine('.hbs', exphbs({
    extname: '.hbs',
    defaultLayout: 'main',
    helpers: {
      isAdmin: (role: string) => role === RolesEnum.admin,
    },
  }));
  app.set('views', viewsPath);
  app.set('view engine', '.hbs');

  const redisClient = redis.createClient({
    url: configService.get<string>('REDIS_URL'),
  });
  const RedisStore = redisStore(session);

  app.use(
    session({
      secret: configService.get<string>('PASSPORT_SESSION_SECRET') as string,
      resave: false,
      saveUninitialized: false,
      store: new RedisStore({
        host: configService.get<string>('REDIS_HOST'),
        port: configService.get<number>('REDIS_PORT') as unknown as number,
        client: redisClient,
        ttl: 666,
      }),
    }),
  );

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

  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 #23
Source File: _mongodb-main.ts    From nest-js-boilerplate with MIT License 5 votes vote down vote up
async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);

  const configService = app.get(ConfigService);

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

  const viewsPath = join(__dirname, '../public/views');

  app.engine('.hbs', exphbs({
    extname: '.hbs',
    defaultLayout: 'main',
    helpers: {
      isAdmin: (role: string) => role === RolesEnum.admin,
    },
  }));
  app.set('views', viewsPath);
  app.set('view engine', '.hbs');

  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());
  app.use(flash());

  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 codeclannigeria-backend with MIT License 4 votes vote down vote up
async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule, {
    cors: true
  });

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

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

  Sentry.init({
    dsn:
      'https://[email protected]/5819318',

    // Set tracesSampleRate to 1.0 to capture 100%
    // of transactions for performance monitoring.
    // We recommend adjusting this value in production
    tracesSampleRate: 1.0
  });

  // filters
  app.useGlobalFilters(new AllExceptionsFilter());
  app.useGlobalFilters(new HttpExceptionFilter());

  // validation
  const { jwtSecret, port, database } = configuration();
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      forbidUnknownValues: true,
      // disableErrorMessages: environment === 'production',
      forbidNonWhitelisted: true,
      transform: true,
      transformOptions: {
        enableImplicitConversion: true
      }
    })
  );

  const MongoStore = connectMongo(session);
  app.set('trust proxy', 1);
  app.setGlobalPrefix('/api');
  app.use(
    session({
      secret: jwtSecret,
      store: new MongoStore({ url: database.uri }),
      resave: false,
      saveUninitialized: false
    })
  );
  app.use(cookieParser());
  app.use(passport.initialize());
  app.use(passport.session());

  const options = new DocumentBuilder()
    .setTitle('CodeClanNigeria API')
    .setDescription('CCNigeria API description')
    .setVersion('1.0')
    .addBearerAuth()
    .build();

  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('api', app, document, {
    swaggerOptions: {
      docExpansion: 'none',
      persistAuthorization: true
    }
  });

  const listener = await app.listen(process.env.PORT || port, function () {
    Logger.log('Listening on port ' + listener.address().port);
  });

  if (module.hot) {
    module.hot.accept();
    module.hot.dispose(() => app.close());
  }
}