Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 235244e

Browse files
authoredOct 4, 2023
Apollo Server 4 Upgrade (#123)
* Removed apollo datasource and initialize method from MongoDataSource * Added type for constructor options argument to include modelOrCollection and optionally a cache * Updated the tests for datasource to accomodate the recent changes * Removed deprecated packages and installed new cache package, updated package info * Added two tests to ensure that you can add a context to the constructor of the api class you extend MongoDataSource to * Updated README and package version * Fixed some mistakes and missing info in the README * Minor fixes to the README * Final changes * Final commit * Fixed typing issue * Updated README and some package.json info * Removed npm version comment * Fixed typo in readme * Fixed module name * Added previous README and added note on versioning to both * Fixed README links * Updated mongoose from v5 to v7 and updated mongodb from v3 to v4 * Updated bson to 5.4.0 and mongodb to 5.7.0
1 parent 6eff2ac commit 235244e

File tree

8 files changed

+8635
-5648
lines changed

8 files changed

+8635
-5648
lines changed
 

‎README.md

Lines changed: 190 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,24 @@
11
[![npm version](https://badge.fury.io/js/apollo-datasource-mongodb.svg)](https://www.npmjs.com/package/apollo-datasource-mongodb)
22

3-
Apollo [data source](https://www.apollographql.com/docs/apollo-server/features/data-sources) for MongoDB
3+
Apollo [data source](https://www.apollographql.com/docs/apollo-server/data/fetching-data) for MongoDB
44

5+
Note: This README applies to the current version 0.6.0 and is meant to be paired with Apollo Server 4.
6+
See the old [README](README.old.md) for versions 0.5.4 and below, if you are using Apollo Server 3.
7+
8+
**Installation**
59
```
610
npm i apollo-datasource-mongodb
711
```
812

9-
This package uses [DataLoader](https://github.com/graphql/dataloader) for batching and per-request memoization caching. It also optionally (if you provide a `ttl`) does shared application-level caching (using either the default Apollo `InMemoryLRUCache` or the [cache you provide to ApolloServer()](https://www.apollographql.com/docs/apollo-server/features/data-sources#using-memcachedredis-as-a-cache-storage-backend)). It does this for the following methods:
13+
This package uses [DataLoader](https://github.com/graphql/dataloader) for batching and per-request memoization caching. It also optionally (if you provide a `ttl`) does shared application-level caching (using either the default Apollo `InMemoryLRUCache` or the [cache you provide to ApolloServer()](https://www.apollographql.com/docs/apollo-server/performance/cache-backends#configuring-external-caching)). It does this for the following methods:
1014

1115
- [`findOneById(id, options)`](#findonebyid)
1216
- [`findManyByIds(ids, options)`](#findmanybyids)
1317
- [`findByFields(fields, options)`](#findbyfields)
1418

15-
1619
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
1720
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
21+
1822
**Contents:**
1923

2024
- [Usage](#usage)
@@ -31,7 +35,6 @@ This package uses [DataLoader](https://github.com/graphql/dataloader) for batchi
3135

3236
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
3337

34-
3538
## Usage
3639

3740
### Basic
@@ -54,6 +57,8 @@ and:
5457

5558
```js
5659
import { MongoClient } from 'mongodb'
60+
import { ApolloServer } from '@apollo/server'
61+
import { startStandaloneServer } from '@apollo/server/standalone'
5762

5863
import Users from './data-sources/Users.js'
5964

@@ -62,23 +67,31 @@ client.connect()
6267

6368
const server = new ApolloServer({
6469
typeDefs,
65-
resolvers,
66-
dataSources: () => ({
67-
users: new Users(client.db().collection('users'))
68-
// OR
69-
// users: new Users(UserModel)
70-
})
70+
resolvers
71+
})
72+
73+
const { url } = await startStandaloneServer(server, {
74+
context: async ({ req }) => ({
75+
dataSources: {
76+
users: new Users({ modelOrCollection: client.db().collection('users') })
77+
// OR
78+
// users: new Users({ modelOrCollection: UserModel })
79+
}
80+
}),
7181
})
7282
```
7383

74-
Inside the data source, the collection is available at `this.collection` (e.g. `this.collection.update({_id: 'foo, { $set: { name: 'me' }}})`). The model (if you're using Mongoose) is available at `this.model` (`new this.model({ name: 'Alice' })`). The request's context is available at `this.context`. For example, if you put the logged-in user's ID on context as `context.currentUserId`:
84+
Inside the data source, the collection is available at `this.collection` (e.g. `this.collection.update({_id: 'foo, { $set: { name: 'me' }}})`). The model (if you're using Mongoose) is available at `this.model` (`new this.model({ name: 'Alice' })`). By default, the API classes you create will not have access to the context. You can either choose to add the data that your API class needs on a case-by-case basis as members of the class, or you can add the entire context as a member of the class if you wish. All you need to do is add the field(s) to the options argument of the constructor and call super passing in options. For example, if you put the logged-in user's ID on context as `context.currentUserId` and you want your Users class to have access to `currentUserId`:
7585

7686
```js
7787
class Users extends MongoDataSource {
78-
...
88+
constructor(options) {
89+
super(options)
90+
this.currentUserId = options.currentUserId
91+
}
7992

8093
async getPrivateUserData(userId) {
81-
const isAuthorized = this.context.currentUserId === userId
94+
const isAuthorized = this.currentUserId === userId
8295
if (isAuthorized) {
8396
const user = await this.findOneById(userId)
8497
return user && user.privateData
@@ -87,15 +100,65 @@ class Users extends MongoDataSource {
87100
}
88101
```
89102

90-
If you want to implement an initialize method, it must call the parent method:
103+
and you would instantiate the Users data source in the context like this
104+
105+
```js
106+
...
107+
const server = new ApolloServer({
108+
typeDefs,
109+
resolvers
110+
})
111+
112+
const { url } = await startStandaloneServer(server, {
113+
context: async ({ req }) => {
114+
const currentUserId = getCurrentUserId(req) // not a real function, for demo purposes only
115+
return {
116+
currentUserId,
117+
dataSources: {
118+
users: new Users({ modelOrCollection: UserModel, currentUserId })
119+
},
120+
}
121+
},
122+
});
123+
```
124+
125+
If you want your data source to have access to the entire context at `this.context`, you need to create a `Context` class so the context can refer to itself as `this` in the constructor for the data source.
126+
See [dataSources](https://www.apollographql.com/docs/apollo-server/migration/#datasources) for more information regarding how data sources changed from Apollo Server 3 to Apollo Server 4.
91127

92128
```js
93129
class Users extends MongoDataSource {
94-
initialize(config) {
95-
super.initialize(config)
96-
...
130+
constructor(options) {
131+
super(options)
132+
this.context = options.context
133+
}
134+
135+
async getPrivateUserData(userId) {
136+
const isAuthorized = this.context.currentUserId === userId
137+
if (isAuthorized) {
138+
const user = await this.findOneById(userId)
139+
return user && user.privateData
140+
}
97141
}
98142
}
143+
144+
...
145+
146+
class Context {
147+
constructor(req) {
148+
this.currentUserId = getCurrentUserId(req), // not a real function, for demo purposes only
149+
this.dataSources = {
150+
users: new Users({ modelOrCollection: UserModel, context: this })
151+
},
152+
}
153+
}
154+
155+
...
156+
157+
const { url } = await startStandaloneServer(server, {
158+
context: async ({ req }) => {
159+
return new Context(req)
160+
},
161+
});
99162
```
100163

101164
If you're passing a Mongoose model rather than a collection, Mongoose will be used for data fetching. All transformations defined 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).
@@ -119,7 +182,8 @@ class Posts extends MongoDataSource {
119182

120183
const resolvers = {
121184
Post: {
122-
author: (post, _, { dataSources: { users } }) => users.getUser(post.authorId)
185+
author: (post, _, { dataSources: { users } }) =>
186+
users.getUser(post.authorId)
123187
},
124188
User: {
125189
posts: (user, _, { dataSources: { posts } }) => posts.getPosts(user.postIds)
@@ -128,11 +192,16 @@ const resolvers = {
128192

129193
const server = new ApolloServer({
130194
typeDefs,
131-
resolvers,
132-
dataSources: () => ({
133-
users: new Users(db.collection('users')),
134-
posts: new Posts(db.collection('posts'))
135-
})
195+
resolvers
196+
})
197+
198+
const { url } = await startStandaloneServer(server, {
199+
context: async ({ req }) => ({
200+
dataSources: {
201+
users: new Users({ modelOrCollection: db.collection('users') }),
202+
posts: new Posts({ modelOrCollection: db.collection('posts') })
203+
}
204+
}),
136205
})
137206
```
138207

@@ -150,11 +219,14 @@ class Users extends MongoDataSource {
150219

151220
updateUserName(userId, newName) {
152221
this.deleteFromCacheById(userId)
153-
return this.collection.updateOne({
154-
_id: userId
155-
}, {
156-
$set: { name: newName }
157-
})
222+
return this.collection.updateOne(
223+
{
224+
_id: userId
225+
},
226+
{
227+
$set: { name: newName }
228+
}
229+
)
158230
}
159231
}
160232

@@ -173,7 +245,7 @@ Here we also call [`deleteFromCacheById()`](#deletefromcachebyid) to remove the
173245

174246
### TypeScript
175247

176-
Since we are using a typed language, we want the provided methods to be correctly typed as well. This requires us to make the `MongoDataSource` class polymorphic. It requires 1-2 template arguments. The first argument is the type of the document in our collection. The second argument is the type of context in our GraphQL server, which defaults to `any`. For example:
248+
Since we are using a typed language, we want the provided methods to be correctly typed as well. This requires us to make the `MongoDataSource` class polymorphic. It requires 1 template argument, which is the type of the document in our collection. If you wish to add additional fields to your data source class, you can extend the typing on constructor options argument to include any fields that you need. For example:
177249

178250
`data-sources/Users.ts`
179251

@@ -189,12 +261,91 @@ interface UserDocument {
189261
interests: [string]
190262
}
191263

192-
// This is optional
193264
interface Context {
194265
loggedInUser: UserDocument
266+
dataSources: any
267+
}
268+
269+
export default class Users extends MongoDataSource<UserDocument> {
270+
protected loggedInUser: UserDocument
271+
272+
constructor(options: { loggedInUser: UserDocument } & MongoDataSourceConfig<UserDocument>) {
273+
super(options)
274+
this.loggedInUser = options.loggedInUser
275+
}
276+
277+
getUser(userId) {
278+
// this.loggedInUser has type `UserDocument` as defined above
279+
// this.findOneById has type `(id: ObjectId) => Promise<UserDocument | null | undefined>`
280+
return this.findOneById(userId)
281+
}
282+
}
283+
```
284+
285+
and:
286+
287+
```ts
288+
import { MongoClient } from 'mongodb'
289+
290+
import Users from './data-sources/Users.ts'
291+
292+
const client = new MongoClient('mongodb://localhost:27017/test')
293+
client.connect()
294+
295+
const server = new ApolloServer({
296+
typeDefs,
297+
resolvers
298+
})
299+
300+
const { url } = await startStandaloneServer(server, {
301+
context: async ({ req }) => {
302+
const loggedInUser = getLoggedInUser(req) // this function does not exist, just for demo purposes
303+
return {
304+
loggedInUser,
305+
dataSources: {
306+
users: new Users({ modelOrCollection: client.db().collection('users'), loggedInUser }),
307+
},
308+
}
309+
},
310+
});
311+
```
312+
313+
You can also opt to pass the entire context into your data source class. You can do so by adding a protected context member
314+
to your data source class and modifying to options argument of the constructor to add a field for the context. Then, call super and
315+
assign the context to the member field on your data source class. Note: context needs to be a class in order to do this.
316+
317+
```ts
318+
import { MongoDataSource } from 'apollo-datasource-mongodb'
319+
import { ObjectId } from 'mongodb'
320+
321+
interface UserDocument {
322+
_id: ObjectId
323+
username: string
324+
password: string
325+
email: string
326+
interests: [string]
327+
}
328+
329+
class Context {
330+
loggedInUser: UserDocument
331+
dataSources: any
332+
333+
constructor(req: any) {
334+
this.loggedInUser = getLoggedInUser(req)
335+
this.dataSources = {
336+
users: new Users({ modelOrCollection: client.db().collection('users'), context: this }),
337+
}
338+
}
195339
}
196340

197-
export default class Users extends MongoDataSource<UserDocument, Context> {
341+
export default class Users extends MongoDataSource<UserDocument> {
342+
protected context: Context
343+
344+
constructor(options: { context: Context } & MongoDataSourceConfig<UserDocument>) {
345+
super(options)
346+
this.context = options.context
347+
}
348+
198349
getUser(userId) {
199350
// this.context has type `Context` as defined above
200351
// this.findOneById has type `(id: ObjectId) => Promise<UserDocument | null | undefined>`
@@ -215,15 +366,17 @@ client.connect()
215366

216367
const server = new ApolloServer({
217368
typeDefs,
218-
resolvers,
219-
dataSources: () => ({
220-
users: new Users(client.db().collection('users'))
221-
// OR
222-
// users: new Users(UserModel)
223-
})
369+
resolvers
224370
})
371+
372+
const { url } = await startStandaloneServer(server, {
373+
context: async ({ req }) => {
374+
return new Context(req)
375+
},
376+
});
225377
```
226378

379+
227380
## API
228381

229382
The type of the `id` argument must match the type used in the database. We currently support ObjectId and string types.

‎README.old.md

Lines changed: 298 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,298 @@
1+
[![npm version](https://badge.fury.io/js/apollo-datasource-mongodb.svg)](https://www.npmjs.com/package/apollo-datasource-mongodb)
2+
3+
Apollo [data source](https://www.apollographql.com/docs/apollo-server/features/data-sources) for MongoDB
4+
5+
Note: This README applies to versions 0.5.4 and below, and it is meant to be paired with Apollo Server 3.
6+
See the [README](README.md) for version 0.6.0, if you are using Apollo Server 4.
7+
8+
```
9+
npm i apollo-datasource-mongodb
10+
```
11+
12+
This package uses [DataLoader](https://github.com/graphql/dataloader) for batching and per-request memoization caching. It also optionally (if you provide a `ttl`) does shared application-level caching (using either the default Apollo `InMemoryLRUCache` or the [cache you provide to ApolloServer()](https://www.apollographql.com/docs/apollo-server/features/data-sources#using-memcachedredis-as-a-cache-storage-backend)). It does this for the following methods:
13+
14+
- [`findOneById(id, options)`](#findonebyid)
15+
- [`findManyByIds(ids, options)`](#findmanybyids)
16+
- [`findByFields(fields, options)`](#findbyfields)
17+
18+
19+
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
20+
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
21+
**Contents:**
22+
23+
- [Usage](#usage)
24+
- [Basic](#basic)
25+
- [Batching](#batching)
26+
- [Caching](#caching)
27+
- [TypeScript](#typescript)
28+
- [API](#api)
29+
- [findOneById](#findonebyid)
30+
- [findManyByIds](#findmanybyids)
31+
- [findByFields](#findbyfields)
32+
- [Examples](#examples)
33+
- [deleteFromCacheById](#deletefromcachebyid)
34+
35+
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
36+
37+
38+
## Usage
39+
40+
### Basic
41+
42+
The basic setup is subclassing `MongoDataSource`, passing your collection or Mongoose model to the constructor, and using the [API methods](#API):
43+
44+
`data-sources/Users.js`
45+
46+
```js
47+
import { MongoDataSource } from 'apollo-datasource-mongodb'
48+
49+
export default class Users extends MongoDataSource {
50+
getUser(userId) {
51+
return this.findOneById(userId)
52+
}
53+
}
54+
```
55+
56+
and:
57+
58+
```js
59+
import { MongoClient } from 'mongodb'
60+
61+
import Users from './data-sources/Users.js'
62+
63+
const client = new MongoClient('mongodb://localhost:27017/test')
64+
client.connect()
65+
66+
const server = new ApolloServer({
67+
typeDefs,
68+
resolvers,
69+
dataSources: () => ({
70+
users: new Users(client.db().collection('users'))
71+
// OR
72+
// users: new Users(UserModel)
73+
})
74+
})
75+
```
76+
77+
Inside the data source, the collection is available at `this.collection` (e.g. `this.collection.update({_id: 'foo, { $set: { name: 'me' }}})`). The model (if you're using Mongoose) is available at `this.model` (`new this.model({ name: 'Alice' })`). The request's context is available at `this.context`. For example, if you put the logged-in user's ID on context as `context.currentUserId`:
78+
79+
```js
80+
class Users extends MongoDataSource {
81+
...
82+
83+
async getPrivateUserData(userId) {
84+
const isAuthorized = this.context.currentUserId === userId
85+
if (isAuthorized) {
86+
const user = await this.findOneById(userId)
87+
return user && user.privateData
88+
}
89+
}
90+
}
91+
```
92+
93+
If you want to implement an initialize method, it must call the parent method:
94+
95+
```js
96+
class Users extends MongoDataSource {
97+
initialize(config) {
98+
super.initialize(config)
99+
...
100+
}
101+
}
102+
```
103+
104+
If you're passing a Mongoose model rather than a collection, Mongoose will be used for data fetching. All transformations defined 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).
105+
106+
### Batching
107+
108+
This is the main feature, and is always enabled. Here's a full example:
109+
110+
```js
111+
class Users extends MongoDataSource {
112+
getUser(userId) {
113+
return this.findOneById(userId)
114+
}
115+
}
116+
117+
class Posts extends MongoDataSource {
118+
getPosts(postIds) {
119+
return this.findManyByIds(postIds)
120+
}
121+
}
122+
123+
const resolvers = {
124+
Post: {
125+
author: (post, _, { dataSources: { users } }) => users.getUser(post.authorId)
126+
},
127+
User: {
128+
posts: (user, _, { dataSources: { posts } }) => posts.getPosts(user.postIds)
129+
}
130+
}
131+
132+
const server = new ApolloServer({
133+
typeDefs,
134+
resolvers,
135+
dataSources: () => ({
136+
users: new Users(db.collection('users')),
137+
posts: new Posts(db.collection('posts'))
138+
})
139+
})
140+
```
141+
142+
### Caching
143+
144+
To enable shared application-level caching, you do everything from the above section, and you add the `ttl` (in seconds) option to `findOneById()`:
145+
146+
```js
147+
const MINUTE = 60
148+
149+
class Users extends MongoDataSource {
150+
getUser(userId) {
151+
return this.findOneById(userId, { ttl: MINUTE })
152+
}
153+
154+
updateUserName(userId, newName) {
155+
this.deleteFromCacheById(userId)
156+
return this.collection.updateOne({
157+
_id: userId
158+
}, {
159+
$set: { name: newName }
160+
})
161+
}
162+
}
163+
164+
const resolvers = {
165+
Post: {
166+
author: (post, _, { users }) => users.getUser(post.authorId)
167+
},
168+
Mutation: {
169+
changeName: (_, { userId, newName }, { users, currentUserId }) =>
170+
currentUserId === userId && users.updateUserName(userId, newName)
171+
}
172+
}
173+
```
174+
175+
Here we also call [`deleteFromCacheById()`](#deletefromcachebyid) to remove the user from the cache when the user's data changes. If we're okay with people receiving out-of-date data for the duration of our `ttl`—in this case, for as long as a minute—then we don't need to bother adding calls to `deleteFromCacheById()`.
176+
177+
### TypeScript
178+
179+
Since we are using a typed language, we want the provided methods to be correctly typed as well. This requires us to make the `MongoDataSource` class polymorphic. It requires 1-2 template arguments. The first argument is the type of the document in our collection. The second argument is the type of context in our GraphQL server, which defaults to `any`. For example:
180+
181+
`data-sources/Users.ts`
182+
183+
```ts
184+
import { MongoDataSource } from 'apollo-datasource-mongodb'
185+
import { ObjectId } from 'mongodb'
186+
187+
interface UserDocument {
188+
_id: ObjectId
189+
username: string
190+
password: string
191+
email: string
192+
interests: [string]
193+
}
194+
195+
// This is optional
196+
interface Context {
197+
loggedInUser: UserDocument
198+
}
199+
200+
export default class Users extends MongoDataSource<UserDocument, Context> {
201+
getUser(userId) {
202+
// this.context has type `Context` as defined above
203+
// this.findOneById has type `(id: ObjectId) => Promise<UserDocument | null | undefined>`
204+
return this.findOneById(userId)
205+
}
206+
}
207+
```
208+
209+
and:
210+
211+
```ts
212+
import { MongoClient } from 'mongodb'
213+
214+
import Users from './data-sources/Users.ts'
215+
216+
const client = new MongoClient('mongodb://localhost:27017/test')
217+
client.connect()
218+
219+
const server = new ApolloServer({
220+
typeDefs,
221+
resolvers,
222+
dataSources: () => ({
223+
users: new Users(client.db().collection('users'))
224+
// OR
225+
// users: new Users(UserModel)
226+
})
227+
})
228+
```
229+
230+
## API
231+
232+
The type of the `id` argument must match the type used in the database. We currently support ObjectId and string types.
233+
234+
### findOneById
235+
236+
`this.findOneById(id, { ttl })`
237+
238+
Resolves to the found document. Uses DataLoader to load `id`. DataLoader uses `collection.find({ _id: { $in: ids } })`. Optionally caches the document if `ttl` is set (in whole positive seconds).
239+
240+
### findManyByIds
241+
242+
`this.findManyByIds(ids, { ttl })`
243+
244+
Calls [`findOneById()`](#findonebyid) for each id. Resolves to an array of documents.
245+
246+
### findByFields
247+
248+
`this.findByFields(fields, { ttl })`
249+
250+
Resolves to an array of documents matching the passed fields. If an empty object is passed as the `fields` parameter, resolves to an array containing all documents in the given collection.
251+
252+
`fields` has this type:
253+
254+
```ts
255+
interface Fields {
256+
[fieldName: string]:
257+
| string
258+
| number
259+
| boolean
260+
| ObjectId
261+
| (string | number | boolean | ObjectId)[]
262+
}
263+
```
264+
265+
#### Examples
266+
267+
```js
268+
// get user by username
269+
// `collection.find({ username: $in: ['testUser'] })`
270+
this.findByFields({
271+
username: 'testUser'
272+
})
273+
274+
// get all users with either the "gaming" OR "games" interest
275+
// `collection.find({ interests: $in: ['gaming', 'games'] })`
276+
this.findByFields({
277+
interests: ['gaming', 'games']
278+
})
279+
280+
// get user by username AND with either the "gaming" OR "games" interest
281+
// `collection.find({ username: $in: ['testUser'], interests: $in: ['gaming', 'games'] })`
282+
this.findByFields({
283+
username: 'testUser',
284+
interests: ['gaming', 'games']
285+
})
286+
```
287+
288+
### deleteFromCacheById
289+
290+
`this.deleteFromCacheById(id)`
291+
292+
Deletes a document from the cache that was fetched with `findOneById` or `findManyByIds`.
293+
294+
### deleteFromCacheByFields
295+
296+
`this.deleteFromCacheByFields(fields)`
297+
298+
Deletes a document from the cache that was fetched with `findByFields`. Fields should be passed in exactly the same way they were used to find with.

‎index.d.ts

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,21 @@
11
declare module 'apollo-datasource-mongodb' {
2-
import { DataSource } from 'apollo-datasource'
2+
import { KeyValueCache } from '@apollo/utils.keyvaluecache'
33
import { Collection as MongoCollection, ObjectId } from 'mongodb'
44
import {
55
Collection as MongooseCollection,
66
Document,
77
Model as MongooseModel,
88
} from 'mongoose'
99

10-
export type Collection<T, U = MongoCollection<T>> = T extends Document
10+
export type Collection<T extends { [key: string]: any }, U = MongoCollection<T>> = T extends Document
1111
? MongooseCollection
1212
: U
1313

1414
export type Model<T, U = MongooseModel<T>> = T extends Document
1515
? U
1616
: undefined
1717

18-
export type ModelOrCollection<T, U = Model<T>> = T extends Document
18+
export type ModelOrCollection<T extends { [key: string]: any }, U = Model<T>> = T extends Document
1919
? U
2020
: Collection<T>
2121

@@ -32,14 +32,16 @@ declare module 'apollo-datasource-mongodb' {
3232
ttl: number
3333
}
3434

35-
export class MongoDataSource<TData, TContext = any> extends DataSource<
36-
TContext
37-
> {
38-
protected context: TContext
35+
export interface MongoDataSourceConfig<TData extends { [key: string]: any }> {
36+
modelOrCollection: ModelOrCollection<TData>
37+
cache?: KeyValueCache<TData>
38+
}
39+
40+
export class MongoDataSource<TData extends { [key: string]: any }> {
3941
protected collection: Collection<TData>
4042
protected model: Model<TData>
4143

42-
constructor(modelOrCollection: ModelOrCollection<TData>)
44+
constructor(options: MongoDataSourceConfig<TData>)
4345

4446
findOneById(
4547
id: ObjectId | string,

‎package-lock.json

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

‎package.json

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "apollo-datasource-mongodb",
3-
"version": "0.5.4",
3+
"version": "0.6.0",
44
"description": "Apollo data source for MongoDB",
55
"main": "dist/index.js",
66
"types": "index.d.ts",
@@ -17,25 +17,19 @@
1717
"node": ">=8"
1818
},
1919
"dependencies": {
20-
"@types/mongodb": "^3.5.27",
21-
"apollo-datasource": "^0.3.1",
22-
"apollo-server-caching": "^0.3.1",
23-
"apollo-server-errors": "^2.4.1",
24-
"bson": "^4.1.0",
20+
"@apollo/utils.keyvaluecache": "^3.0.0",
21+
"bson": "^5.4.0",
2522
"dataloader": "^1.4.0"
2623
},
27-
"peerDependencies": {
28-
"mongoose": "*"
29-
},
3024
"devDependencies": {
3125
"@babel/cli": "^7.10.3",
3226
"@babel/core": "^7.10.3",
3327
"@babel/preset-env": "^7.10.3",
3428
"babel-jest": "^24.9.0",
3529
"graphql": "^14.6.0",
3630
"jest": "^24.9.0",
37-
"mongodb": "^3.5.9",
38-
"mongoose": "^5.13.8",
31+
"mongodb": "^5.7.0",
32+
"mongoose": "^7.3.2",
3933
"prettier": "^1.19.1",
4034
"release": "^6.3.0",
4135
"waait": "^1.0.5"

‎src/__tests__/cache.test.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { InMemoryLRUCache } from 'apollo-server-caching'
1+
import { InMemoryLRUCache } from '@apollo/utils.keyvaluecache'
22
import wait from 'waait'
33
import { ObjectId } from 'mongodb'
44
import { EJSON } from 'bson'
@@ -14,7 +14,7 @@ import {
1414
import { log } from '../helpers'
1515

1616
const hexId = '5cf82e14a220a607eb64a7d4'
17-
const objectID = ObjectId(hexId)
17+
const objectID = new ObjectId(hexId)
1818

1919
const docs = {
2020
one: {
@@ -23,7 +23,7 @@ const docs = {
2323
tags: ['foo', 'bar']
2424
},
2525
two: {
26-
_id: ObjectId(),
26+
_id: new ObjectId(),
2727
foo: 'bar'
2828
},
2929
three: {

‎src/__tests__/datasource.test.js

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,18 @@ import mongoose, { Schema, model } from 'mongoose'
44
import { MongoDataSource } from '../datasource'
55
import { isModel, isCollectionOrModel, getCollection } from '../helpers'
66

7-
mongoose.set('useFindAndModify', false)
8-
97
class Users extends MongoDataSource {
10-
initialize(config) {
11-
super.initialize(config)
8+
constructor(options) {
9+
super(options)
10+
this.context = options.context
1211
}
1312
}
1413

1514
describe('MongoDataSource', () => {
1615
it('sets up caching functions', () => {
1716
const users = {}
18-
const source = new Users(users)
19-
source.initialize()
17+
const source = new Users({modelOrCollection: users})
18+
2019
expect(source.findOneById).toBeDefined()
2120
expect(source.findByFields).toBeDefined()
2221
expect(source.deleteFromCacheById).toBeDefined()
@@ -42,7 +41,7 @@ const connect = async () => {
4241
}
4342

4443
const hexId = '5cf82e14a220a607eb64a7d4'
45-
const objectID = ObjectId(hexId)
44+
const objectID = new ObjectId(hexId)
4645

4746
describe('Mongoose', () => {
4847
let UserModel
@@ -103,27 +102,23 @@ describe('Mongoose', () => {
103102
})
104103

105104
test('Data Source with Model', async () => {
106-
const users = new Users(UserModel)
107-
users.initialize()
105+
const users = new Users({ modelOrCollection: UserModel })
108106
const user = await users.findOneById(alice._id)
107+
109108
expect(user.name).toBe('Alice')
110109
expect(user.id).toBe(alice._id.toString())
111110
})
112111

113112
test('Data Source with Collection', async () => {
114-
const users = new Users(userCollection)
115-
users.initialize()
116-
113+
const users = new Users({ modelOrCollection: userCollection})
117114
const user = await users.findOneById(alice._id)
118115

119116
expect(user.name).toBe('Alice')
120117
expect(user.id).toBeUndefined()
121118
})
122119

123120
test('nested findByFields', async () => {
124-
const users = new Users(userCollection)
125-
users.initialize()
126-
121+
const users = new Users({ modelOrCollection: userCollection })
127122
const [user] = await users.findByFields({ 'nested._id': objectID })
128123

129124
expect(user).toBeDefined()
@@ -135,4 +130,18 @@ describe('Mongoose', () => {
135130
expect(res1[0].name).toBe('Bob')
136131
expect(res2[0]).toBeUndefined()
137132
})
133+
134+
test('Data Source with Context', async () => {
135+
const users = new Users({ modelOrCollection: UserModel, context: { token: '123' }})
136+
137+
expect(users.context.token).toBe('123')
138+
})
139+
140+
test('Data Source with Context that contains a User', async () => {
141+
const users = new Users({ modelOrCollection: userCollection, context: { user: alice }})
142+
const user = await users.findOneById(alice._id)
143+
144+
expect(user.name).toBe('Alice')
145+
expect(users.context.user.name).toBe(user.name)
146+
})
138147
})

‎src/datasource.js

Lines changed: 9 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,24 @@
1-
import { DataSource } from 'apollo-datasource'
2-
import { ApolloError } from 'apollo-server-errors'
3-
import { InMemoryLRUCache } from 'apollo-server-caching'
1+
import { GraphQLError } from 'graphql'
2+
import { InMemoryLRUCache } from '@apollo/utils.keyvaluecache'
43

54
import { createCachingMethods } from './cache'
65
import { isCollectionOrModel, isModel } from './helpers'
76

8-
class MongoDataSource extends DataSource {
9-
constructor(collection) {
10-
super()
117

12-
if (!isCollectionOrModel(collection)) {
13-
throw new ApolloError(
8+
class MongoDataSource {
9+
constructor({modelOrCollection, cache}) {
10+
if (!isCollectionOrModel(modelOrCollection)) {
11+
throw new GraphQLError(
1412
'MongoDataSource constructor must be given a collection or Mongoose model'
1513
)
1614
}
1715

18-
if (isModel(collection)) {
19-
this.model = collection
16+
if (isModel(modelOrCollection)) {
17+
this.model = modelOrCollection
2018
this.collection = this.model.collection
2119
} else {
22-
this.collection = collection
20+
this.collection = modelOrCollection
2321
}
24-
}
25-
26-
// https://github.com/apollographql/apollo-server/blob/master/packages/apollo-datasource/src/index.ts
27-
initialize({ context, cache } = {}) {
28-
this.context = context
2922

3023
const methods = createCachingMethods({
3124
collection: this.collection,

0 commit comments

Comments
 (0)
Please sign in to comment.