import { IncomingMessage } from 'http' ; import { VoyagerContext } from './VoyagerContext' ; import { VoyagerContextProviderConfig } from './VoyagerContextConfig' ; type ContextFunction = ( object : any ) => any ; /**
 * The VoyagerContextProvider will be used to extend the GraphQL context
 * With info from the various Voyager framework components
 * e.g. Security, client info.
 */ export class ApolloVoyagerContextProvider { public config : VoyagerContextProviderConfig ; public authContextProvider : any ; public userContextFunction : any ; public userContextObject : any ; constructor ( config ) { this . config = config ; if ( typeof this . config . userContext === 'function' ) { this . userContextFunction = this . config . userContext ; } else if ( isObject ( this . config . userContext ) ) { this . userContextObject = this . config . userContext ; } this . authContextProvider = this . config . securityService . getAuthContextProvider ( ) ; } /**
     * returns the context object or function that should be passed into new ApolloServer()
     */ public getContext ( ) { const voyagerContextProvider = this ; return async function combineContexts ( { req } ) : Promise < object > { const defaultContext = voyagerContextProvider . getDefaultContext ( { req } ) ; let userContext = voyagerContextProvider . buildUserContext ( { req } ) ; if ( userContext instanceof Promise ) { userContext = await userContext ; } return { ... userContext , ... defaultContext } ; } ; } private buildUserContext ( { req } ) { let userContext ; if ( this . userContextFunction ) { userContext = this . userContextFunction ( { req } ) ; } else if ( this . userContextObject ) { userContext = this . userContextObject ; } return userContext ; } private getDefaultContext ( { req } ) { const authContextProvider = new this . authContextProvider ( { req } ) ; const defaultContext = { request : req , auth : authContextProvider } ; if ( this . authContextProvider . contextKey ) { defaultContext [ this . authContextProvider . contextKey ] = authContextProvider ; } return defaultContext ; } } function isObject ( val ) { if ( val === null ) { return false ; } return ( typeof val === 'object' && ! Array . isArray ( val ) ) ; } export { VoyagerContextProviderConfig } from './VoyagerContextConfig' ;