|
| 1 | +import cats.effect.{ExitCode, IO, IOApp} |
| 2 | +import com.comcast.ip4s.IpLiteralSyntax |
| 3 | +import graphql.{AppContext, GraphQLSchema, ProductGraphQLSchema, UserGraphQLSchema} |
| 4 | +import http.{GraphQLExecutor, GraphQLServer} |
| 5 | +import io.circe.Json |
| 6 | +import sangria.federation.v2.Federation |
| 7 | +import sangria.marshalling.InputUnmarshaller |
| 8 | +import sangria.renderer.QueryRenderer |
| 9 | +import sangria.schema.Schema |
| 10 | +import service.{ProductResearchService, ProductService, UserService} |
| 11 | + |
| 12 | +object Main extends IOApp { |
| 13 | + |
| 14 | + override def run(args: List[String]): IO[ExitCode] = (args match { |
| 15 | + case "printSchema" :: Nil => printSchema |
| 16 | + case _ => runGraphQLServer |
| 17 | + }).as(ExitCode.Success) |
| 18 | + |
| 19 | + private def printSchema: IO[Unit] = |
| 20 | + for { |
| 21 | + schema <- IO(schemaAndUm).map(_._1) |
| 22 | + _ <- IO.println(QueryRenderer.renderPretty(schema.toAst)) |
| 23 | + } yield () |
| 24 | + |
| 25 | + private def runGraphQLServer: IO[Unit] = |
| 26 | + for { |
| 27 | + ctx <- appContext |
| 28 | + executor <- graphQLExecutor(ctx) |
| 29 | + host = host"0.0.0.0" |
| 30 | + port = port"4001" |
| 31 | + _ <- IO.println(s"starting GraphQL HTTP server on http://$host:$port") |
| 32 | + _ <- GraphQLServer.bind(executor, host, port).use(_ => IO.never) |
| 33 | + } yield () |
| 34 | + |
| 35 | + private def appContext: IO[AppContext] = IO { |
| 36 | + new AppContext { |
| 37 | + override def productService: ProductService = ProductService.inMemory |
| 38 | + override def productResearchService: ProductResearchService = ProductResearchService.inMemory |
| 39 | + override def userService: UserService = UserService.inMemory |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + private def schemaAndUm: (Schema[AppContext, Unit], InputUnmarshaller[Json]) = |
| 44 | + Federation.federate( |
| 45 | + GraphQLSchema.schema, |
| 46 | + sangria.marshalling.circe.CirceInputUnmarshaller, |
| 47 | + ProductGraphQLSchema.productResolver, |
| 48 | + ProductGraphQLSchema.deprecatedProductResolver, |
| 49 | + ProductGraphQLSchema.productResearchResolver, |
| 50 | + UserGraphQLSchema.userResolver |
| 51 | + ) |
| 52 | + |
| 53 | + private def graphQLExecutor(context: AppContext): IO[GraphQLExecutor[AppContext]] = IO { |
| 54 | + val (schema, um) = schemaAndUm |
| 55 | + GraphQLExecutor(schema, context)(um) |
| 56 | + } |
| 57 | +} |
0 commit comments