Skip to content

Commit 2b95618

Browse files
author
Matt
committed
refactor loaders
1 parent eeb910a commit 2b95618

File tree

2 files changed

+10
-6
lines changed

2 files changed

+10
-6
lines changed

src/loaders.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import DataLoader from 'dataloader'
2+
import { Comment } from './db'
3+
4+
const findCommentsLoader = new DataLoader(async posts => {
5+
const comments = await Comment.query().whereIn('post_id', posts.map(p => p.id))
6+
return posts.map(p => comments.filter(c => c.post_id === p.id))
7+
})
8+
9+
export default findCommentsLoader

src/schema.js

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { makeExecutableSchema } from 'graphql-tools'
22
import { importSchema } from 'graphql-import'
33
import jwt from 'jsonwebtoken'
44
import bcrypt from 'bcrypt'
5-
import DataLoader from 'dataloader'
5+
import findCommentsLoader from './loaders'
66
import { User, Post, Comment } from './db'
77

88
const typeDefs = importSchema('./schema/schema.graphql')
@@ -15,11 +15,6 @@ const authenticated = fn => (parent, args, context, info) => {
1515
throw new Error('User is not authenticated')
1616
}
1717

18-
const findCommentsLoader = new DataLoader(async posts => {
19-
const comments = await Comment.query().whereIn('post_id', posts.map(p => p.id))
20-
return posts.map(p => comments.filter(c => c.post_id === p.id))
21-
})
22-
2318
export const resolvers = {
2419
Query: {
2520
viewer: authenticated((parent, args, context) => context.user)

0 commit comments

Comments
 (0)