Opening a database connection is an expensive process, and that's why we use Connection pool to reduce the cost. And it also allows us to have a good transaction management in a single session that uses different providers.
We define two providers in
Pool is application scoped and
DatabaseProvider is session-scoped.
So, it will provide us different clients from connection pool for each session/network request.
See Dependency Injection to learn more about provider scopes.
You can define external classes as Provider in GraphQL Modules. In the example above,
Poolwill be constructed once in the application scope.
And we will use the
OnResponse hook to release the client to the pool after we've done with it.
See Dependency Injection to learn more about hooks.
DatabaseProvider will be created on a session level while the instance of
Pool will be the same instance always in the application level.
You can also combine it with data-loaders to solve the
N+1 problem in SQL queries like below:
The example above also uses sql-template-strings, which allows ES6 template strings for prepared SQL statements.
Thanks to this approach, you can use transactions inside GraphQL Modules like below:
MongoDB with generic-pool
You can create a MongoDB pool and connect it at the beginning of each network request until the network request is finished.