Skip to content

Commit 6f39f9b

Browse files
authored
Include Model on createCachingMethods loader (#30)
* Include Model on createCachingMethods loader * Add ID matchers for Model and Collection tests
1 parent ec63e00 commit 6f39f9b

File tree

3 files changed

+23
-10
lines changed

3 files changed

+23
-10
lines changed

src/__tests__/datasource.test.js

+4-2
Original file line numberDiff line numberDiff line change
@@ -75,17 +75,19 @@ describe('Mongoose', () => {
7575
expect(getCollection(UserModel).collectionName).toBe('users')
7676
})
7777

78-
test('data source', async () => {
78+
test('Data Source with Model', async () => {
7979
const users = new Users(UserModel)
8080
users.initialize()
8181
const user = await users.findOneById(alice._id)
8282
expect(user.name).toBe('Alice')
83+
expect(user.id).toBe(alice._id.toString())
8384
})
8485

85-
test('collection', async () => {
86+
test('Data Source with Collection', async () => {
8687
const users = new Users(userCollection)
8788
users.initialize()
8889
const user = await users.findOneById(alice._id)
8990
expect(user.name).toBe('Alice')
91+
expect(user.id).toBeUndefined()
9092
})
9193
})

src/cache.js

+18-7
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import DataLoader from 'dataloader'
22

3-
import { getCollection } from './helpers'
3+
import { getCollection, isModel } from './helpers'
44

55
// https://github.com/graphql/dataloader#batch-function
66
const orderDocs = ids => docs => {
@@ -12,12 +12,23 @@ const orderDocs = ids => docs => {
1212
}
1313

1414
export const createCachingMethods = ({ collection, cache }) => {
15-
const loader = new DataLoader(ids =>
16-
collection
17-
.find({ _id: { $in: ids } })
18-
.toArray()
19-
.then(orderDocs(ids))
20-
)
15+
const loader = new DataLoader((ids) => {
16+
const res = collection.find({
17+
_id: {
18+
$in: ids,
19+
},
20+
});
21+
22+
let promise;
23+
24+
if (isModel(collection)) {
25+
promise = res.exec();
26+
} else {
27+
promise = res.toArray();
28+
}
29+
30+
return promise.then(orderDocs(ids));
31+
});
2132

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

src/datasource.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ class MongoDataSource extends DataSource {
2828
this.context = context
2929

3030
const methods = createCachingMethods({
31-
collection: this.collection,
31+
collection: this.model || this.collection,
3232
cache: cache || new InMemoryLRUCache()
3333
})
3434

0 commit comments

Comments
 (0)