Skip to content

Commit ec63e00

Browse files
authored
Add TypeScript usage example (#33)
1 parent 97302e7 commit ec63e00

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

README.md

+53
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ This package uses [DataLoader](https://github.com/graphql/dataloader) for batchi
2020
- [Basic](#basic)
2121
- [Batching](#batching)
2222
- [Caching](#caching)
23+
- [TypeScript](#typescript)
2324
- [API](#api)
2425
- [findOneById](#findonebyid)
2526
- [findManyByIds](#findmanybyids)
@@ -165,6 +166,58 @@ const resolvers = {
165166

166167
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()`.
167168

169+
### TypeScript
170+
171+
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:
172+
173+
`data-sources/Users.ts`
174+
175+
```ts
176+
import { MongoDataSource } from 'apollo-datasource-mongodb'
177+
import { ObjectId } from 'mongodb'
178+
179+
interface UserDocument {
180+
_id: ObjectId
181+
username: string
182+
password: string
183+
email: string
184+
}
185+
186+
// This is optional
187+
interface Context {
188+
loggedInUser: UserDocument
189+
}
190+
191+
export default class Users extends MongoDataSource<UserDocument, Context> {
192+
getUser(userId) {
193+
// this.context has type `Context` as defined above
194+
// this.findOneById has type `(id: ObjectId) => Promise<UserDocument | null | undefined>`
195+
return this.findOneById(userId)
196+
}
197+
}
198+
```
199+
200+
and:
201+
202+
```ts
203+
import { MongoClient } from 'mongodb'
204+
205+
import Users from './data-sources/Users.ts'
206+
207+
const client = new MongoClient('mongodb://localhost:27017/test')
208+
client.connect()
209+
210+
const server = new ApolloServer({
211+
typeDefs,
212+
resolvers,
213+
dataSources: () => ({
214+
users: new Users(client.db().collection('users'))
215+
// OR
216+
// users: new Users(UserModel)
217+
})
218+
})
219+
```
220+
168221
## API
169222

170223
### findOneById

0 commit comments

Comments
 (0)