import { Application } from 'express' ; import { Config } from 'apollo-server-core' ; import { ApolloServer } from 'apollo-server-express' ; import { InMemoryLRUCache } from 'apollo-server-caching' ; import { mocks , schemaDirectives , resolvers , typeDefs } from '../../graphql/setupSchema' ; import * as bodyParser from 'body-parser' ; const expressJwt = require ( 'express-jwt' ) ; import * as fs from 'fs' ; const DataLoader = require ( 'dataloader' ) ; import { fetchPeopleWithPlanet , fetchPeople , fetchPlanet , fetchStarship } from '../../graphql/dataloader/starwars' ; import StarwarsAPI from '../../graphql/datasource/starwars-api' ; const tracing = process . env . GRAPHQL_TRACING !== undefined && process . env . GRAPHQL_TRACING === 'true' ? true : false ; const getGraphQLConfig = ( ) : Config => { const peopleLoader = new DataLoader ( keys => Promise . all ( keys . map ( fetchPeople ) ) ) ; const planetLoader = new DataLoader ( keys => Promise . all ( keys . map ( fetchPlanet ) ) ) ; const starshipLoader = new DataLoader ( keys => Promise . all ( keys . map ( fetchStarship ) ) ) ; const peopleWithPlanetLoader = new DataLoader ( keys => Promise . all ( keys . map ( fetchPeopleWithPlanet ) ) ) ; const getuser = req => { if ( process . env . JWT_AUTH === 'true' ) { return req . user ? req . user : Promise . resolve ( '' ) ; } } ; const playground = process . env . GRAPHQL_PLAYGROUND !== undefined && process . env . GRAPHQL_PLAYGROUND === 'true' ? true : false ; const serverMocks = process . env . GRAPHQL_MOCK !== undefined && process . env . GRAPHQL_MOCK === 'true' ? mocks : false ; const myStarwarsAPI = new StarwarsAPI ( ) ; return { typeDefs , resolvers , dataSources : ( ) => { return { starwarsAPI : myStarwarsAPI } ; } , cache : new InMemoryLRUCache ( { maxSize : 100 } ) , schemaDirectives , mocks : serverMocks , tracing , playground , introspection : true , context : async ( { req , connection } ) => { if ( connection ) { return { } ; } else { const user = getuser ( req ) ; return { user , peopleLoader , planetLoader , starshipLoader , peopleWithPlanetLoader } ; } } } ; } ; param app export const configGraphQL = ( app ) : ApolloServer => { if ( process . env . JWT_AUTH === 'true' ) { const RSA_PUBLIC_KEY = fs . readFileSync ( process . env . RSA_PUBLIC_KEY_FILE ) ; app . use ( '/graphql' , bodyParser . json ( ) , expressJwt ( { secret : RSA_PUBLIC_KEY , credentialsRequired : false } ) ) ; } const server = new ApolloServer ( getGraphQLConfig ( ) ) ; const path = '/graphql' ; server . applyMiddleware ( { app , path } ) ; return server ; } ;