Skip to content

Commit 1c48d72

Browse files
author
Matt
committed
now with data loader
1 parent 764f2fb commit 1c48d72

File tree

3 files changed

+13
-1
lines changed

3 files changed

+13
-1
lines changed

package-lock.json

Lines changed: 5 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
"babel-preset-env": "^1.6.1",
1212
"bcrypt": "^1.0.3",
1313
"body-parser": "^1.18.2",
14+
"dataloader": "^1.4.0",
1415
"express": "^4.16.2",
1516
"express-jwt": "^5.3.0",
1617
"graphql": "^0.12.3",

src/schema.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +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'
56
import { User, Post, Comment } from './db'
67

78
const typeDefs = importSchema('./schema/schema.graphql')
@@ -14,6 +15,11 @@ const authenticated = fn => (parent, args, context, info) => {
1415
throw new Error('User is not authenticated')
1516
}
1617

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+
1723
export const resolvers = {
1824
Query: {
1925
viewer: authenticated((parent, args, context) => context.user)
@@ -32,7 +38,7 @@ export const resolvers = {
3238
},
3339
Post: {
3440
user: async post => User.query().findOne({ id: post.author_id }),
35-
comments: async post => Comment.query().where({ post_id: post.id })
41+
comments: async post => findCommentsLoader.load(post)
3642
},
3743
Mutation: {
3844
createToken: async (parent, { email, password }) => {

0 commit comments

Comments
 (0)