Database Connection Pooling
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.
The first example uses PostgreSQL and node-postgres below. The other example combines generic-pool with MongoDB which doesn't have the pooling feature in the native driver internally.
#
PostgreSQLWe define two providers in DatabaseModule
: 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.
database.module.ts
You can define external classes as Provider in GraphQL Modules. In the example above,
Pool
will 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.
database.provider.ts
You can also combine it with data-loaders to solve the N+1
problem in SQL queries like below:
database.provider.ts
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:
user.entity.ts
users.provider.ts
#
MongoDB with generic-poolYou can create a MongoDB pool and connect it at the beginning of each network request until the network request is finished.
database.module.ts
database.provider.ts