Skip to content

Commit 235244e

Browse files
authored
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

8 files changed

+8635
-5648
lines changed

README.md

+190-37
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.

0 commit comments

Comments
 (0)