title: Gracefully closing connection of DB using TypeORM in NestJs
body: <p>So, before I go deep in the problem let me explain you the basic of my app.</p>
  <p>I have connection to <strong>DB(TypeOrm), Kafka(kafkajs)</strong> in my app.</p>
  <p>My app is the <strong>Consumer of 1 topic</strong> which:</p>
  <ol>
  <li>Gets some data in the callback handler, and puts that data in one table using TypeORM Entity</li>
  <li>Maintains the <strong>Global map</strong> (in some Singleton Instance of a class) with some id (that I get in data of point 1).</li>
  </ol>
  <p>At the time of <strong>app getting shutdown</strong>, my task is:</p>
  <ol>
  <li><strong>Disconnect all the consumers</strong> of the topics (this service is connected to) from the Kafka</li>
  <li><strong>Traverse the Global Map</strong> (point 2) and <strong>repark the message</strong> in the some topic</li>
  <li><strong>Disconnect the DB connections</strong> using the close method.</li>
  </ol>
  <p>Here are some piece of code that might help you understand how I added the life cycle events on Server in NestJs.</p>
  <p><strong>system.server.life.cycle.events.ts</strong></p>
  <pre><code>@Injectable()
  export class SystemServerLifeCycleEventsShared implements BeforeApplicationShutdown {
      constructor(@Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger, private readonly someService: SomeService) {}
  
      async beforeApplicationShutdown(signal: string) {
          const [err] = await this.someService.handleAbruptEnding();
  
          if (err) this.logger.info(`beforeApplicationShutdown, error::: ${JSON.stringify(err)}`);
          this.logger.info(`beforeApplicationShutdown, signal ${signal}`);
      }
  }
  </code></pre>
  <p><strong>some.service.ts</strong></p>
  <pre><code>export class SomeService {
      constructor(private readonly kafkaConnector: KafkaConnector, private readonly postgresConnector: PostgresConnector) {}
      
      public async handleAbruptEnding(): Promise&lt;any&gt; {
          
          await this.kafkaConnector.disconnectAllConsumers();
          for(READ_FROM_GLOBAL_STORE) { 
               await this.kafkaConnector.function.call.to.repark.the.message();
          }
          
          await this.postgresConnector.disconnectAllConnections();
  
          return true;
      }
  }
  </code></pre>
  <p><strong>postgres.connector.ts</strong></p>
  <pre><code>export class PostgresConnector {
      private connectionManager: ConnectionManager; 
      constructor () {
          this.connectionManager = getConnectionManager();
      }
  
      public async disconnectAllConnections(): Promise&lt;void[]&gt; {
          const connectionClosePromises: Promise&lt;void&gt; = [];
          connectionManager.connections?.forEach((connection) =&gt; {
              if (connection.isConnected) connectionClosePromises.push(connection.close());
          });
  
          return Promise.all(connectionClosePromises);
      }
  }
  </code></pre>
  <p><em>ConnectionManager&amp; getConnectionManager() imported from TypeORM module.</em></p>
  <p>Now here are some unusual exceptions / behavior I am facing:</p>
  <ol>
  <li><p>Disconnect all connections is throwing exception/error as in quote:</p>
  <p><strong>ERROR [TypeOrmModule] Cannot execute operation on &quot;default&quot; connection because connection is not yet established.</strong>
  If connection is not yet established then how come my <strong>isConnected</strong> came true inside of <strong>if</strong>. I am not getting any clue anywhere how is this possible. And how to do graceful shutdown of the connection in TypeORM.</p>
  </li>
  <li><p>Do we really need to handle the closure of the connection in TypeORM or it internally handles it.</p>
  </li>
  <li><p>Even if, TypeORM handles the connection closure internally, how could we achieve it explicitly.</p>
  </li>
  <li><p>Is there any callback that can be triggered in case the connection is disconnected properly so that I am sure, that disconnection actually happened from the db.</p>
  </li>
  <li><p>Some of the messages are coming after I press CTRL + C (mimicking the abrupt/closure of the process of my server) and the control comes back to Terminal. This means, some thread is coming back after the handle returns to my terminal (, no clue, how would I handle this, since if you see, my handleAbruptHandling is <strong>awaited</strong> and also, I cross checked all the promises are being awaited properly.)</p>
  </li>
  </ol>
  <p>Some of the things to know:</p>
  <ol>
  <li>I properly added my module to create the hooks of server life cycle events.</li>
  <li>Injected the objects in almost all the classes properly.</li>
  <li>Not getting any DI issue from NEST and server is getting started properly.</li>
  </ol>
  <p>Please shed some light and let me know how can I gracefully disconnect from db using typeorm api inside NestJs in case of abrupt closure.</p>
  <p>Thanks in advance and happy coding :)</p>