/modules/core/server-scala/src/main/scala/core/app/ModuleApp.scala

https://github.com/sysgears/apollo-universal-starter-kit · Scala · 60 lines · 51 code · 9 blank · 0 comment · 0 complexity · 0ebde2e49b48c65f0c5daba578442054 MD5 · raw file

  1. package core.app
  2. import akka.actor.ActorSystem
  3. import akka.http.scaladsl.Http
  4. import akka.http.scaladsl.server.Directives._
  5. import akka.stream.ActorMaterializer
  6. import ch.megard.akka.http.cors.scaladsl.CorsDirectives.cors
  7. import ch.megard.akka.http.cors.scaladsl.settings.CorsSettings
  8. import com.google.inject.Guice.createInjector
  9. import common.AppInitialization
  10. import common.graphql.UserContext
  11. import common.graphql.schema.{GraphQL, GraphQLSchema}
  12. import common.routes.graphql.{GraphQLRoute, HttpHandler, WebSocketHandler}
  13. import common.slick.SchemaInitializer
  14. import core.guice.injection.InjectorProvider._
  15. import monix.execution.Scheduler
  16. import sangria.execution.{Executor, QueryReducer}
  17. import shapes.ServerModule
  18. import scala.concurrent.ExecutionContext
  19. trait ModuleApp extends App with AppInitialization {
  20. def createApp(serverModule: ServerModule[UserContext, SchemaInitializer[_]]): Unit = {
  21. createInjector(serverModule.foldBindings.bindings)
  22. serverModule.fold
  23. implicit val system: ActorSystem = inject[ActorSystem]
  24. implicit val materializer: ActorMaterializer = inject[ActorMaterializer]
  25. implicit val executionContext: ExecutionContext = inject[ExecutionContext]
  26. implicit val scheduler: Scheduler = inject[Scheduler]
  27. val graphQL = new GraphQLSchema(serverModule)
  28. val graphQlExecutor = executor(graphQL)
  29. val httpHandler = new HttpHandler(graphQL, graphQlExecutor)
  30. val webSocketHandler = new WebSocketHandler(graphQL, graphQlExecutor)
  31. val graphQLRoute = new GraphQLRoute(httpHandler, webSocketHandler, graphQL)
  32. val routes = serverModule.routes + graphQLRoute.routes
  33. val corsSettings = CorsSettings.apply(system)
  34. withActionsBefore {
  35. serverModule.slickSchemas.map(_.createAndSeed()).toSeq
  36. }(
  37. Http().bindAndHandle(
  38. cors(corsSettings)(routes.reduce(_ ~ _)),
  39. interface = "0.0.0.0"
  40. )
  41. )
  42. }
  43. def executor(graphQL: GraphQL)(implicit executionContext: ExecutionContext): Executor[UserContext, Unit] = Executor(
  44. schema = graphQL.schema,
  45. queryReducers = List(
  46. QueryReducer.rejectMaxDepth[UserContext](graphQL.maxQueryDepth),
  47. QueryReducer
  48. .rejectComplexQueries[UserContext](graphQL.maxQueryComplexity, (_, _) => new Exception("maxQueryComplexity"))
  49. )
  50. )
  51. }