@@ -12,6 +12,7 @@ import {
1212 testkit ,
1313} from '../src' ;
1414import { ExecutionContext } from '../src/di' ;
15+ import { ApolloServer } from '@apollo/server' ;
1516
1617const Test = new InjectionToken < string > ( 'test' ) ;
1718
@@ -541,6 +542,100 @@ test('Operation scoped provider should be created once per GraphQL Operation', a
541542 expect ( loadSpy ) . toHaveBeenCalledWith ( 1 ) ;
542543} ) ;
543544
545+ test ( 'Operation scoped provider should be created once per GraphQL Operation (Apollo Server)' , async ( ) => {
546+ const constructorSpy = jest . fn ( ) ;
547+ const loadSpy = jest . fn ( ) ;
548+
549+ @Injectable ( {
550+ scope : Scope . Operation ,
551+ } )
552+ class Dataloader {
553+ constructor ( @Inject ( CONTEXT ) context : GraphQLModulesGlobalContext ) {
554+ constructorSpy ( context ) ;
555+ }
556+
557+ load ( id : number ) {
558+ loadSpy ( id ) ;
559+ return {
560+ id,
561+ title : 'Sample Title' ,
562+ } ;
563+ }
564+ }
565+
566+ const postsModule = createModule ( {
567+ id : 'posts' ,
568+ providers : [ Dataloader ] ,
569+ typeDefs : gql `
570+ type Post {
571+ id: Int!
572+ title: String!
573+ }
574+ type Query {
575+ post(id: Int!): Post!
576+ }
577+ ` ,
578+ resolvers : {
579+ Query : {
580+ post (
581+ _parent : { } ,
582+ args : { id : number } ,
583+ { injector } : GraphQLModulesModuleContext
584+ ) {
585+ return injector . get ( Dataloader ) . load ( args . id ) ;
586+ } ,
587+ } ,
588+ } ,
589+ } ) ;
590+
591+ const app = createApplication ( {
592+ modules : [ postsModule ] ,
593+ } ) ;
594+
595+ const apolloServer = new ApolloServer ( {
596+ gateway : app . createApolloGateway ( ) ,
597+ } ) ;
598+
599+ const query = gql `
600+ {
601+ foo: post(id: 1) {
602+ id
603+ title
604+ }
605+ bar: post(id: 1) {
606+ id
607+ title
608+ }
609+ }
610+ ` ;
611+
612+ const result = await apolloServer . executeOperation ( {
613+ query,
614+ } ) ;
615+
616+ if ( result . body . kind === 'incremental' ) {
617+ throw new Error ( 'Expected non-incremental response' ) ;
618+ }
619+
620+ // Should resolve data correctly
621+ expect ( result . body . singleResult . errors ) . toBeUndefined ( ) ;
622+ expect ( result . body . singleResult . data ) . toEqual ( {
623+ foo : {
624+ id : 1 ,
625+ title : 'Sample Title' ,
626+ } ,
627+ bar : {
628+ id : 1 ,
629+ title : 'Sample Title' ,
630+ } ,
631+ } ) ;
632+
633+ expect ( constructorSpy ) . toHaveBeenCalledTimes ( 1 ) ;
634+
635+ expect ( loadSpy ) . toHaveBeenCalledTimes ( 2 ) ;
636+ expect ( loadSpy ) . toHaveBeenCalledWith ( 1 ) ;
637+ } ) ;
638+
544639test ( 'Singleton scoped provider should be created once' , async ( ) => {
545640 const constructorSpy = jest . fn ( ) ;
546641
0 commit comments