Skip to content

Commit

Permalink
Step 13.6: Define Database provider
Browse files Browse the repository at this point in the history
  • Loading branch information
kamilkisiela authored and Urigo committed May 20, 2020
1 parent 0df0f93 commit 925e8f4
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 6 deletions.
6 changes: 0 additions & 6 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { GraphQLModule } from '@graphql-modules/core';
import http from 'http';
import { app } from './app';
import { origin, port } from './env';
import { MyContext } from './context';

import usersModule from './modules/users';
import chatsModule from './modules/chats';
Expand All @@ -18,11 +17,6 @@ const server = new ApolloServer({
schema: rootModule.schema,
context: rootModule.context,
subscriptions: rootModule.subscriptions,
formatResponse: (res: any, { context }: any) => {
context.db.release();

return res;
},
});

server.applyMiddleware({
Expand Down
26 changes: 26 additions & 0 deletions modules/common/database.provider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Injectable, ProviderScope } from '@graphql-modules/di';
import { OnResponse } from '@graphql-modules/core';
import { Pool, PoolClient } from 'pg';

@Injectable({
scope: ProviderScope.Session,
})
export class Database implements OnResponse {
private instance: PoolClient;

constructor(private pool: Pool) {}

async onRequest() {
this.instance = await this.pool.connect();
}

onResponse() {
if (this.instance) {
this.instance.release();
}
}

async getClient() {
return this.instance;
}
}
9 changes: 9 additions & 0 deletions modules/common/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { GraphQLModule } from '@graphql-modules/core';
import { gql } from 'apollo-server-express';
import { DateTimeResolver, URLResolver } from 'graphql-scalars';
import { Pool } from 'pg';
import { pool } from '../../db';
import { Resolvers } from '../../types/graphql';
import { Database } from './database.provider';

const { PostgresPubSub } = require('graphql-postgres-subscriptions');

Expand Down Expand Up @@ -40,6 +42,13 @@ export default new GraphQLModule({
name: 'common',
typeDefs,
resolvers,
providers: () => [
{
provide: Pool,
useValue: pool,
},
Database,
],
async context({ res, connection }) {
let db;

Expand Down

0 comments on commit 925e8f4

Please sign in to comment.