11import { DataSource } from "apollo-datasource" ;
22import { KeyValueCache } from "apollo-server-caching" ;
3- import { Collection , FindOptions } from "mongodb" ;
3+ import { Collection , Document , FindOptions } from "mongodb" ;
44
55type DataSourceOperation = "findOne" | "find" | "count" ;
66
7- export default class MongoDataSource implements DataSource {
7+ export default class MongoDataSource < TSchema extends Document = Document >
8+ implements DataSource
9+ {
810 context : any ;
9- collection : Collection < Document > ;
11+ collection : Collection < TSchema > ;
1012
1113 cachePrefix : string ;
1214
1315 private pendingResults : { key : string ; promise : Promise < any > } [ ] = [ ] ;
1416
15- constructor ( collection : Collection < Document > , public cache ?: KeyValueCache ) {
17+ constructor ( collection : Collection < TSchema > , public cache ?: KeyValueCache ) {
1618 this . collection = collection ;
1719
1820 this . cachePrefix = `mongo-${ this . collection . dbName } -${ this . collection . collectionName } -` ;
@@ -42,7 +44,7 @@ export default class MongoDataSource implements DataSource {
4244 options : { ttl : number ; findOptions ?: FindOptions < Document > } = {
4345 ttl : 60
4446 }
45- ) : Promise < any [ ] > {
47+ ) : Promise < TSchema [ ] > {
4648 const cacheKey = this . getCacheKey ( "find" , fields , options ) ,
4749 cacheDoc = await this . cache ?. get ( cacheKey ) ;
4850
@@ -62,10 +64,10 @@ export default class MongoDataSource implements DataSource {
6264
6365 async findOne (
6466 fields : any = { } ,
65- options : { ttl : number ; findOptions ?: FindOptions < Document > } = {
67+ options : { ttl : number ; findOptions ?: FindOptions } = {
6668 ttl : 60
6769 }
68- ) {
70+ ) : Promise < TSchema | null > {
6971 const cacheKey = this . getCacheKey ( "findOne" , fields , options ) ,
7072 cacheDoc = await this . cache ?. get ( cacheKey ) ;
7173
@@ -84,15 +86,15 @@ export default class MongoDataSource implements DataSource {
8486 async delete (
8587 type : DataSourceOperation ,
8688 fields : any ,
87- options : { findOptions ?: FindOptions < Document > } = { }
89+ options : { findOptions ?: FindOptions } = { }
8890 ) {
8991 return await this . cache ?. delete ( this . getCacheKey ( type , fields , options ) ) ;
9092 }
9193
9294 private getCacheKey (
9395 type : DataSourceOperation ,
9496 fields : any ,
95- options : { findOptions ?: FindOptions < Document > } = { }
97+ options : { findOptions ?: FindOptions } = { }
9698 ) {
9799 return (
98100 this . cachePrefix +
0 commit comments