Skip to content

Commit

Permalink
Step 14.6: Use Dataloader in Chats
Browse files Browse the repository at this point in the history
  • Loading branch information
kamilkisiela authored and Urigo committed Jul 20, 2019
1 parent 5013804 commit 3c11ad9
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
39 changes: 36 additions & 3 deletions modules/chats/chats.provider.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,50 @@
import { Injectable, Inject, ProviderScope } from '@graphql-modules/di';
import { QueryResult } from 'pg';
import sql from 'sql-template-strings';
import DataLoader from 'dataloader';
import { Database } from '../common/database.provider';
import { PubSub } from '../common/pubsub.provider';

type ChatsByUser = { userId: string };
type ChatByUser = { userId: string; chatId: string };
type ChatById = { chatId: string };
type ChatsKey = ChatById | ChatByUser | ChatsByUser;

function isChatsByUser(query: any): query is ChatsByUser {
return query.userId && !query.chatId;
}

function isChatByUser(query: any): query is ChatByUser {
return query.userId && query.chatId;
}

@Injectable({
scope: ProviderScope.Session,
})
export class Chats {
@Inject() private db: Database;
@Inject() private pubsub: PubSub;

private loaders = {
chats: new DataLoader<ChatsKey, QueryResult['rows']>(keys => {
return Promise.all(
keys.map(async query => {
if (isChatsByUser(query)) {
return this._findChatsByUser(query.userId);
}

if (isChatByUser(query)) {
return this._findChatByUser(query);
}

return this._findChatById(query.chatId);
})
);
}),
};

async findChatsByUser(userId: string) {
return this._findChatsByUser(userId);
return this.loaders.chats.load({ userId });
}

private async _findChatsByUser(userId: string) {
Expand All @@ -25,7 +58,7 @@ export class Chats {
}

async findChatByUser({ chatId, userId }: { chatId: string; userId: string }) {
const rows = await this._findChatByUser({ chatId, userId });
const rows = await this.loaders.chats.load({ chatId, userId });

return rows[0] || null;
}
Expand All @@ -48,7 +81,7 @@ export class Chats {
}

async findChatById(chatId: string) {
const rows = await this._findChatById(chatId);
const rows = await this.loaders.chats.load({ chatId });
return rows[0] || null;
}

Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
"cookie": "0.4.0",
"cookie-parser": "1.4.4",
"cors": "2.8.5",
"dataloader": "1.4.0",
"express": "4.17.1",
"graphql": "14.4.2",
"graphql-import": "0.7.1",
Expand Down

0 comments on commit 3c11ad9

Please sign in to comment.