7

At my first project we used express and mysql library without any ORM, and we opened connection when controller started and closed this connection in finaly block. I always thought that this method is right.

But now I started to do an app with NestJS + TypeORM, and when my server starts - connection is ready opened! I wondered is it OK, started to google but confused even more.

For example people say that

"You have to open connection only when you need it, and close it immediately after using, because you shouldn't keep 1 opened connection, other users possibly need it".

Also they say:

"You have to use connection pool. Connection pool it is opening 1+ connections and keeping them open. When some thread in your app need it, it won't waste a time on opening"..

WHAT? These two sentences exclude each other.

So,

Question 1: who is right?

Question 2:

If TypeORM uses 'Connection pool', then what is the advantage of it, if my controller will always use 'default connection'?

    @Injectable()
    export class UsersService {
      constructor(
        @InjectRepository(User)
        private usersRepository: Repository<User>,
      ) {}
    
      findAll(): Promise<User[]> {
        return this.usersRepository.find();
      }
    }

If 1kk users request this controller at the same time - TypeORM won't create additional connections in userpool to prevent the overloading of one connection. So, what sense does TypeORM connection pool makes?

1 Answer 1

0

Question 1: that depend on logic and the context of you application, for me neither are wrong nor right.

Qustion 2: the connection pool will open DB connections as it need them to maximase performance. If you application have concurrent users, it make sense to use many connections to DB. You should delegate the opening and closing of DB connections to the connection pool manager. You can limit the number of connection to the DB thogh (https://github.com/typeorm/typeorm/blob/master/docs/connection-options.md#common-connection-options).

Regards

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.