title: "ConnectionNotFoundError: Connection "default" was not found" - class attribute
body: <p>I'm learning NodeJS and the task is to build a simple messaging service. The teacher is using SQLite3, but I decided to use Postgres since it's the DB we use in our company projects.</p>
  <p>Error: &quot;ConnectionNotFoundError: Connection &quot;default&quot; was not found&quot;</p>
  <pre class="lang-js prettyprint-override"><code>// server.ts
  
  import 'reflect-metadata';
  import express from 'express';
  import { createConnection } from 'typeorm';
  
  import router from './router';
  
  (async () =&gt; {
    const PORT = 3333;
  
    console.log('before');
    await createConnection();
    console.log('after');
  
    const app = express();
  
    app.use(express.json());
    app.use(express.urlencoded({ extended: true }));
  
    app.use(router);
  
    app.listen(PORT, () =&gt; {
      console.log(`App is running on port ${PORT}`);
    });
  })();
  
  </code></pre>
  <p>I have the following <code>MessagesService</code></p>
  <pre class="lang-js prettyprint-override"><code>// this works just fine
  class MessagesService {
    async create({ user_id, text, admin_id }: MessagesCreateInterface): Promise&lt;Message&gt; {
      const repository = getCustomRepository(MessagesRepository);
  
      const message = repository.create({
        admin_id,
        text,
        user_id,
      });
  
      await repository.save(message);
  
      return message;
    }
  
  
    async listByUser(user_id: string): Promise&lt;Array&lt;Message&gt;&gt; {
      const repository = getCustomRepository(MessagesRepository);
      const messages = await repository.find({ user_id });
      return messages;
    }
  }
  </code></pre>
  <p>Since <code>getCustomRepository</code> is called in both functions, and tried converting it to a class attribute:</p>
  <pre class="lang-js prettyprint-override"><code>class MessagesService {
    repository: MessagesRepository;
  
    constructor() {
      console.log('constructor');
      this.repository = getCustomRepository(MessagesRepository);
    }
    ...
  }
  
  </code></pre>
  <p>But then I get <code>ConnectionNotFoundError: Connection &quot;default&quot; was not found.</code>.</p>
  <h3>Experiments</h3>
  <ol>
  <li><p>Using a <code>setTimeout</code> inside <code>constructor</code>: The connection is accessed.</p>
  </li>
  <li><p>Consoles.log: I get &quot;before&quot; and &quot;constructor&quot; print, but not &quot;after&quot;.</p>
  </li>
  </ol>
  <p>Can someone help me understand what's going on? As I'm using async/await, <code>MessageService</code> shouldn't be called until the connection was established. Am I'm breaking some pattern here?</p>