Skip to content

Commit 7c90f2d

Browse files
authored
Merge pull request #1 from nnoce14:apollo-server-4-upgrade
Apollo Server 4 Upgrade
2 parents 6eff2ac + 652760e commit 7c90f2d

File tree

7 files changed

+387
-209
lines changed

7 files changed

+387
-209
lines changed

README.md

Lines changed: 160 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,20 @@
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+
MongoDB [data source](https://www.apollographql.com/docs/apollo-server/data/fetching-data) for Apollo Server 4
44

55
```
6-
npm i apollo-datasource-mongodb
6+
npm i apollo-mongo-datasource
77
```
88

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:
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/performance/cache-backends#configuring-external-caching)). It does this for the following methods:
1010

1111
- [`findOneById(id, options)`](#findonebyid)
1212
- [`findManyByIds(ids, options)`](#findmanybyids)
1313
- [`findByFields(fields, options)`](#findbyfields)
1414

15-
1615
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
1716
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
17+
1818
**Contents:**
1919

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

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

34-
3534
## Usage
3635

3736
### Basic
@@ -41,7 +40,7 @@ The basic setup is subclassing `MongoDataSource`, passing your collection or Mon
4140
`data-sources/Users.js`
4241

4342
```js
44-
import { MongoDataSource } from 'apollo-datasource-mongodb'
43+
import { MongoDataSource } from 'apollo-mongo-datasource'
4544

4645
export default class Users extends MongoDataSource {
4746
getUser(userId) {
@@ -54,6 +53,8 @@ and:
5453

5554
```js
5655
import { MongoClient } from 'mongodb'
56+
import { ApolloServer } from '@apollo/server'
57+
import { startStandaloneServer } from '@apollo/server/standalone'
5758

5859
import Users from './data-sources/Users.js'
5960

@@ -62,20 +63,28 @@ client.connect()
6263

6364
const server = new ApolloServer({
6465
typeDefs,
65-
resolvers,
66-
dataSources: () => ({
67-
users: new Users(client.db().collection('users'))
68-
// OR
69-
// users: new Users(UserModel)
70-
})
66+
resolvers
67+
})
68+
69+
const { url } = await startStandaloneServer(server, {
70+
context: async ({ req }) => ({
71+
dataSources: {
72+
users: new Users({ modelOrCollection: client.db().collection('users') })
73+
// OR
74+
// users: new Users({ modelOrCollection: UserModel })
75+
}
76+
}),
7177
})
7278
```
7379

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`:
80+
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' })`). In Apollo Server 3, the context was automatically handled by the abstract DataSource class from apollo-datasource. This package has been deprecated, so the DataSource class has been removed from this package, as well as the initialize method. 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 as private 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 to the options argument of the constructor and call super. Then, 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`:
7581

7682
```js
7783
class Users extends MongoDataSource {
78-
...
84+
constructor(options) {
85+
super(options)
86+
this.context = options.context
87+
}
7988

8089
async getPrivateUserData(userId) {
8190
const isAuthorized = this.context.currentUserId === userId
@@ -87,12 +96,34 @@ class Users extends MongoDataSource {
8796
}
8897
```
8998

90-
If you want to implement an initialize method, it must call the parent method:
99+
and you would instantiate the Users class like this
91100

92101
```js
93-
class Users extends MongoDataSource {
94-
initialize(config) {
95-
super.initialize(config)
102+
...
103+
const server = new ApolloServer({
104+
typeDefs,
105+
resolvers
106+
})
107+
108+
const { url } = await startStandaloneServer(server, {
109+
context: async ({ req }) => ({
110+
dataSources: {
111+
users: new Users({ modelOrCollection: UserModel, context: { currentUserId: '123' } })
112+
}
113+
}),
114+
});
115+
```
116+
117+
If you want your data source to have access to the entire context, you need to create a Context class so the context can refer to itself as this in the constructor for the data source.
118+
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.
119+
120+
```js
121+
class Context {
122+
constructor() {
123+
this.dataSources = {
124+
users: new Users({ modelOrCollection: UserModel, context: this })
125+
},
126+
this.currentUserId = '123',
96127
...
97128
}
98129
}
@@ -119,7 +150,8 @@ class Posts extends MongoDataSource {
119150

120151
const resolvers = {
121152
Post: {
122-
author: (post, _, { dataSources: { users } }) => users.getUser(post.authorId)
153+
author: (post, _, { dataSources: { users } }) =>
154+
users.getUser(post.authorId)
123155
},
124156
User: {
125157
posts: (user, _, { dataSources: { posts } }) => posts.getPosts(user.postIds)
@@ -128,11 +160,16 @@ const resolvers = {
128160

129161
const server = new ApolloServer({
130162
typeDefs,
131-
resolvers,
132-
dataSources: () => ({
133-
users: new Users(db.collection('users')),
134-
posts: new Posts(db.collection('posts'))
135-
})
163+
resolvers
164+
})
165+
166+
const { url } = await startStandaloneServer(server, {
167+
context: async ({ req }) => ({
168+
dataSources: {
169+
users: new Users({ modelOrCollection: db.collection('users') }),
170+
posts: new Posts({ modelOrCollection: db.collection('posts') })
171+
}
172+
}),
136173
})
137174
```
138175

@@ -150,11 +187,14 @@ class Users extends MongoDataSource {
150187

151188
updateUserName(userId, newName) {
152189
this.deleteFromCacheById(userId)
153-
return this.collection.updateOne({
154-
_id: userId
155-
}, {
156-
$set: { name: newName }
157-
})
190+
return this.collection.updateOne(
191+
{
192+
_id: userId
193+
},
194+
{
195+
$set: { name: newName }
196+
}
197+
)
158198
}
159199
}
160200

@@ -173,12 +213,77 @@ Here we also call [`deleteFromCacheById()`](#deletefromcachebyid) to remove the
173213

174214
### TypeScript
175215

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:
216+
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`. We can choose to either pass the necessary data from context to the data source by field, or give the data source class access to the entire context. For example:
177217

178218
`data-sources/Users.ts`
179219

180220
```ts
181-
import { MongoDataSource } from 'apollo-datasource-mongodb'
221+
import { MongoDataSource } from 'apollo-mongo-datasource'
222+
import { ObjectId } from 'mongodb'
223+
224+
interface UserDocument {
225+
_id: ObjectId
226+
username: string
227+
password: string
228+
email: string
229+
interests: [string]
230+
}
231+
232+
// This is optional
233+
interface Context {
234+
loggedInUser: UserDocument
235+
}
236+
237+
export default class Users extends MongoDataSource<UserDocument, Context> {
238+
protected loggedInUser: UserDocument;
239+
240+
constructor(options: { loggedInUser: UserDocument } & MongoDataSourceConfig<TData>) {
241+
super(options);
242+
this.loggedInUser = options.loggedInUser;
243+
}
244+
245+
getUser(userId) {
246+
// this.loggedInUser has type `UserDocument` as defined above
247+
// this.findOneById has type `(id: ObjectId) => Promise<UserDocument | null | undefined>`
248+
return this.findOneById(userId)
249+
}
250+
}
251+
```
252+
253+
and:
254+
255+
```ts
256+
import { MongoClient } from 'mongodb'
257+
258+
import Users from './data-sources/Users.ts'
259+
260+
const client = new MongoClient('mongodb://localhost:27017/test')
261+
client.connect()
262+
263+
const server = new ApolloServer({
264+
typeDefs,
265+
resolvers
266+
})
267+
268+
const { url } = await startStandaloneServer(server, {
269+
context: async ({ req }) => {
270+
const loggedInUser = getLoggedInUser(req); // this function does not exist, just for demo purposes
271+
return {
272+
loggedInUser,
273+
dataSources: {
274+
users: new Users({ modelOrCollection: client.db().collection('users'), loggedInUser})
275+
},
276+
};
277+
},
278+
});
279+
```
280+
281+
You can also opt to pass the entire context into your data source class. You can do so by adding a protected context member
282+
to your data source class and modifying to options argument of the constructor to add a field for the context. Then, call super and
283+
assign the context to the member field on your data source class.
284+
285+
```ts
286+
import { MongoDataSource } from 'apollo-mongo-datasource'
182287
import { ObjectId } from 'mongodb'
183288

184289
interface UserDocument {
@@ -195,6 +300,13 @@ interface Context {
195300
}
196301

197302
export default class Users extends MongoDataSource<UserDocument, Context> {
303+
protected context: Context;
304+
305+
constructor(options: { context: Context } & MongoDataSourceConfig<TData>) {
306+
super(options);
307+
this.context = options.context;
308+
}
309+
198310
getUser(userId) {
199311
// this.context has type `Context` as defined above
200312
// this.findOneById has type `(id: ObjectId) => Promise<UserDocument | null | undefined>`
@@ -215,15 +327,23 @@ client.connect()
215327

216328
const server = new ApolloServer({
217329
typeDefs,
218-
resolvers,
219-
dataSources: () => ({
220-
users: new Users(client.db().collection('users'))
221-
// OR
222-
// users: new Users(UserModel)
223-
})
330+
resolvers
224331
})
332+
333+
const { url } = await startStandaloneServer(server, {
334+
context: async ({ req }) => {
335+
const loggedInUser = getLoggedInUser(req); // this function does not exist, just for demo purposes
336+
return {
337+
loggedInUser,
338+
dataSources: {
339+
users: new Users({ modelOrCollection: client.db().collection('users'), context: this })
340+
},
341+
};
342+
},
343+
});
225344
```
226345

346+
227347
## API
228348

229349
The type of the `id` argument must match the type used in the database. We currently support ObjectId and string types.
@@ -293,3 +413,6 @@ Deletes a document from the cache that was fetched with `findOneById` or `findMa
293413
`this.deleteFromCacheByFields(fields)`
294414

295415
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.
416+
417+
## Forked and extended from
418+
- [The GraphQLGuide's Apollo data source for MongoDB](https://github.com/GraphQLGuide/apollo-datasource-mongodb)

index.d.ts

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
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,
@@ -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> {
36+
modelOrCollection: ModelOrCollection<TData>
37+
cache?: KeyValueCache<TData>
38+
}
39+
40+
export class MongoDataSource<TData> {
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,

0 commit comments

Comments
 (0)