HTTPS
HTTPS protokolidan foydalanadigan ilova yaratish uchun NestFactory class'ining create() metodiga uzatiladigan options obyektida httpsOptions property'sini belgilang:
HTTPS protokolidan foydalanadigan ilova yaratish uchun NestFactory class'ining create() metodiga uzatiladigan options obyektida httpsOptions property'sini belgilang:
1const httpsOptions = {
2 key: fs.readFileSync('./secrets/private-key.pem'),
3 cert: fs.readFileSync('./secrets/public-certificate.pem'),
4};
5const app = await NestFactory.create(AppModule, {
6 httpsOptions,
7});
8await app.listen(process.env.PORT ?? 3000);Agar FastifyAdapter ishlatsangiz, ilovani quyidagicha yarating:
1const app = await NestFactory.create<NestFastifyApplication>(
2 AppModule,
3 new FastifyAdapter({ https: httpsOptions }),
4);Bir vaqtda ishlaydigan bir nechta server
Quyidagi recipe bir vaqtning o'zida bir nechta port'ni tinglaydigan Nest ilovani qanday instantiate qilishni ko'rsatadi. Masalan, bitta oddiy HTTP port va bitta HTTPS port.
1const httpsOptions = {
2 key: fs.readFileSync('./secrets/private-key.pem'),
3 cert: fs.readFileSync('./secrets/public-certificate.pem'),
4};
5
6const server = express();
7const app = await NestFactory.create(AppModule, new ExpressAdapter(server));
8await app.init();
9
10const httpServer = http.createServer(server).listen(3000);
11const httpsServer = https.createServer(httpsOptions, server).listen(443);http.createServer / https.createServer ni o'zimiz chaqirganimiz sababli, app.close chaqirilganda yoki termination signal kelganda NestJS ularni avtomatik yopmaydi. Shu ishni o'zimiz bajarishimiz kerak:
1@Injectable()
2export class ShutdownObserver implements OnApplicationShutdown {
3 private httpServers: http.Server[] = [];
4
5 public addHttpServer(server: http.Server): void {
6 this.httpServers.push(server);
7 }
8
9 public async onApplicationShutdown(): Promise<void> {
10 await Promise.all(
11 this.httpServers.map(
12 (server) =>
13 new Promise((resolve, reject) => {
14 server.close((error) => {
15 if (error) {
16 reject(error);
17 } else {
18 resolve(null);
19 }
20 });
21 }),
22 ),
23 );
24 }
25}
26
27const shutdownObserver = app.get(ShutdownObserver);
28shutdownObserver.addHttpServer(httpServer);
29shutdownObserver.addHttpServer(httpsServer);ExpressAdapter@nestjs/platform-express package'idan import qilinadi. http va https package'lari esa Node.js'ning native package'lari hisoblanadi.
Warning Bu recipe GraphQL Subscriptions bilan ishlamaydi.