| 20 | ], |
| 21 | }) |
| 22 | export class ApolloConfiguration implements ILifeCycle { |
| 23 | private serverRecords: Array<{ |
| 24 | app: any; |
| 25 | server: any; |
| 26 | schema: any; |
| 27 | subscriptionServer?: any; |
| 28 | }> = []; |
| 29 | |
| 30 | @Inject() |
| 31 | applicationManager: MidwayApplicationManager; |
| 32 | |
| 33 | @Inject() |
| 34 | configService: MidwayConfigService; |
| 35 | |
| 36 | @Inject() |
| 37 | graphqlService: GraphQLService; |
| 38 | |
| 39 | @Inject() |
| 40 | apolloService: ApolloService; |
| 41 | |
| 42 | async onReady(container: IMidwayContainer) { |
| 43 | const config = |
| 44 | this.configService.getConfiguration<ApolloConfigurationOptions>('apollo'); |
| 45 | const apps = this.applicationManager.getApplications(['koa', 'express']); |
| 46 | |
| 47 | if (!apps.length) { |
| 48 | return; |
| 49 | } |
| 50 | |
| 51 | const resolvers = this.graphqlService.buildResolvers(config, container); |
| 52 | const baseDir = container.get<string>('baseDir'); |
| 53 | |
| 54 | for (const app of apps) { |
| 55 | const schema = this.apolloService.createSchema( |
| 56 | config, |
| 57 | resolvers, |
| 58 | baseDir |
| 59 | ); |
| 60 | const server = await this.apolloService.createServer(config, schema); |
| 61 | const middleware = this.apolloService.createMiddleware( |
| 62 | server, |
| 63 | config, |
| 64 | app.getNamespace() === 'express' |
| 65 | ); |
| 66 | app.useMiddleware(middleware as any); |
| 67 | this.serverRecords.push({ |
| 68 | app, |
| 69 | server, |
| 70 | schema, |
| 71 | }); |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | async onServerReady() { |
| 76 | const config = |
| 77 | this.configService.getConfiguration<ApolloConfigurationOptions>('apollo'); |
| 78 | for (const record of this.serverRecords) { |
| 79 | record.subscriptionServer = this.apolloService.createSubscriptionServer( |