Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,8 @@ class Users extends MongoDataSource {
}
```

If you're passing a Mongoose model rather than a collection, Mongoose will be used for data fetching. All transformations definded on that model (virtuals, plugins, etc.) will be applied to your data before caching, just like you would expect it. If you're using reference fields, you might be interested in checking out [mongoose-autopopulate](https://www.npmjs.com/package/mongoose-autopopulate).

### Batching

This is the main feature, and is always enabled. Here's a full example:
Expand Down Expand Up @@ -144,8 +146,8 @@ class Users extends MongoDataSource {

updateUserName(userId, newName) {
this.deleteFromCacheById(userId)
return this.collection.updateOne({
_id: userId
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

only saw this after my commit, i got my editor set up to remove trailing spaces automagically. unrelated ofc, but i guess they technically have no business being there ;)

return this.collection.updateOne({
_id: userId
}, {
$set: { name: newName }
})
Expand All @@ -157,7 +159,7 @@ const resolvers = {
author: (post, _, { users }) => users.getUser(post.authorId)
},
Mutation: {
changeName: (_, { userId, newName }, { users, currentUserId }) =>
changeName: (_, { userId, newName }, { users, currentUserId }) =>
currentUserId === userId && users.updateUserName(userId, newName)
}
}
Expand Down
21 changes: 14 additions & 7 deletions src/cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,20 @@ const orderDocs = ids => docs => {
return ids.map(id => idMap[id])
}

export const createCachingMethods = ({ collection, cache }) => {
const loader = new DataLoader(ids =>
collection
.find({ _id: { $in: ids } })
.toArray()
.then(orderDocs(ids))
)
export const createCachingMethods = ({ collection, model, cache }) => {
const loader = model
? new DataLoader(ids =>
model
.find({ _id: { $in: ids } })
.exec()
.then(orderDocs(ids))
)
: new DataLoader(ids =>
collection
.find({ _id: { $in: ids } })
.toArray()
.then(orderDocs(ids))
)

const cachePrefix = `mongo-${getCollection(collection).collectionName}-`

Expand Down
1 change: 1 addition & 0 deletions src/datasource.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ class MongoDataSource extends DataSource {

const methods = createCachingMethods({
collection: this.collection,
model: this.model,
cache: cache || new InMemoryLRUCache()
})

Expand Down