import { GraphQLSchema } from 'graphql' ; import nock from 'nock' ; import { getGraphQLParameters , processRequest as processGraphQLHelixRequest } from 'graphql-helix' ; export function mockGraphQLServer ( { schema , host , path , intercept , method = 'POST' , } ) { const handler = async function ( this , uri , body ) { if ( intercept ) { intercept ( this ) ; } const uriObj = new URL ( host + uri ) ; const queryObj = { } ; uriObj . searchParams . forEach ( ( val , key ) => ( queryObj [ key ] = val ) ) ; const request = { body , headers : this . req . headers , method , query : queryObj , } ; const { operationName , query , variables } = getGraphQLParameters ( request ) ; const result = await processGraphQLHelixRequest ( { operationName , query , variables , request , schema , } ) ; if ( result . type === 'RESPONSE' ) { const headers = { } ; result . headers . forEach ( ( { name , value } ) => ( headers [ name ] = value ) ) ; return [ result . status , result . payload , headers ] ; } else { return [ 500 , 'Not implemented' ] ; } } ; switch ( method ) { case 'GET' : return nock ( host ) . get ( path ) . reply ( handler ) ; case 'POST' : return nock ( host ) . post ( path ) . reply ( handler ) ; } return null ; }