diff --git a/packages/core/nest-application.ts b/packages/core/nest-application.ts index 3b25d587738..ef123cde060 100644 --- a/packages/core/nest-application.ts +++ b/packages/core/nest-application.ts @@ -177,6 +177,10 @@ export class NestApplication } public async init(): Promise { + if (this.isInitialized) { + return this; + } + this.applyOptions(); await this.httpAdapter?.init(); diff --git a/packages/core/test/nest-application.spec.ts b/packages/core/test/nest-application.spec.ts index e9fb0ab66bf..fefd38d5f2b 100644 --- a/packages/core/test/nest-application.spec.ts +++ b/packages/core/test/nest-application.spec.ts @@ -7,6 +7,7 @@ import { NestApplication } from '../nest-application'; import { mapToExcludeRoute } from './../middleware/utils'; import { NoopHttpAdapter } from './utils/noop-adapter.spec'; import { MicroserviceOptions } from '@nestjs/microservices'; +import * as sinon from 'sinon'; describe('NestApplication', () => { describe('Hybrid Application', () => { @@ -79,4 +80,28 @@ describe('NestApplication', () => { }); }); }); + describe('Double initialization', () => { + it('should initialize application only once', async () => { + const noopHttpAdapter = new NoopHttpAdapter({}); + const httpAdapterSpy = sinon.spy(noopHttpAdapter); + + const applicationConfig = new ApplicationConfig(); + + const container = new NestContainer(applicationConfig); + container.setHttpAdapter(noopHttpAdapter); + + const instance = new NestApplication( + container, + noopHttpAdapter, + applicationConfig, + new GraphInspector(container), + {}, + ); + + await instance.init(); + await instance.init(); + + expect(httpAdapterSpy.init.calledOnce).to.be.true; + }); + }); });