{"id":15065898,"url":"https://github.com/redbubble/finch-sangria","last_synced_at":"2025-10-05T03:30:30.968Z","repository":{"id":150814138,"uuid":"65544723","full_name":"redbubble/finch-sangria","owner":"redbubble","description":"A simple wrapper for using Sangria from within Finch.","archived":true,"fork":false,"pushed_at":"2018-01-10T03:16:40.000Z","size":88,"stargazers_count":33,"open_issues_count":0,"forks_count":2,"subscribers_count":51,"default_branch":"master","last_synced_at":"2025-01-23T21:33:00.679Z","etag":null,"topics":["finch","graphiql","graphql","graphql-server","sangria"],"latest_commit_sha":null,"homepage":null,"language":"Scala","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/redbubble.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2016-08-12T10:20:28.000Z","updated_at":"2024-03-17T22:45:23.000Z","dependencies_parsed_at":"2023-05-21T15:45:37.204Z","dependency_job_id":null,"html_url":"https://github.com/redbubble/finch-sangria","commit_stats":null,"previous_names":[],"tags_count":14,"template":false,"template_full_name":null,"purl":"pkg:github/redbubble/finch-sangria","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/redbubble%2Ffinch-sangria","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/redbubble%2Ffinch-sangria/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/redbubble%2Ffinch-sangria/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/redbubble%2Ffinch-sangria/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/redbubble","download_url":"https://codeload.github.com/redbubble/finch-sangria/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/redbubble%2Ffinch-sangria/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":278403999,"owners_count":25981198,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-05T02:00:06.059Z","response_time":54,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["finch","graphiql","graphql","graphql-server","sangria"],"created_at":"2024-09-25T00:57:08.403Z","updated_at":"2025-10-05T03:30:30.665Z","avatar_url":"https://github.com/redbubble.png","language":"Scala","funding_links":[],"categories":[],"sub_categories":[],"readme":"[![Build status](https://img.shields.io/travis/redbubble/finch-sangria/master.svg)](https://travis-ci.org/redbubble/finch-sangria)\n\n# Finch GraphQL support\n\nSome simple wrappers around [Sangria](http://sangria-graphql.org) to support its use in [Finch](https://github.com/finagle/finch).\n\nIt is a small layer, that is reasonably opininated, which may not be to your liking. In particular:\n\n* We transport GraphQL queries as JSON, over HTTP. This necessitates some nasties from time to time.\n* We use Twitter classes instead of the standard library, for things like `Future` and `Try`.\n* We use `Future`s containing `Option`s or `Either`s instead a failing `Future`. Failing `Future`s are only used for\n  things that we'd not reasonably expect a client to be able to handle (i.e. something catastrophic).\n* We handle variables in the form of a JSON encoded string (for example from GraphiQL), as well as a straight JSON object.\n* We do our best to give back semi-sane HTTP status codes.\n* We expect that you want strong types for things.\n\nThere are some things that need improvement, including:\n\n* We are hard coded to Circe, it should be fairly easy to decouple it should you so wish.\n* In the same vein, the executor returns `Json`, mainly because of the `CirceResultMarshaller`. Ideally both of these\n  would use some form of class that represented the variables/results, and defined an `InputUnmarshaller` and a\n  `ResultMarshaller` for them respectively. In particular, this leads to the unpleasantness with the re-parsing of the\n  JSON returned from the underlying executor to find the status of the result.\n\nIf you like this, you might like other open source code from Redbubble:\n\n* [rb-scala-utils](https://github.com/redbubble/rb-scala-utils) - Miscellaneous utilities (common code) for building\n  Scala-based services, using Finch (on which this project depends).\n* [finch-template](https://github.com/redbubble/finch-template) - A template project for Finch-based services.\n* [rb-graphql-template](https://github.com/redbubble/rb-graphql-template) - A template for Scala HTTP GraphQL services.\n* [finagle-hawk](https://github.com/redbubble/finagle-hawk) - HTTP Holder-Of-Key Authentication Scheme for Finagle.\n\n# Setup\n\nYou will need to add something like the following to your `build.sbt`:\n\n```scala\nresolvers += Resolver.jcenterRepo\n\nlibraryDependencies += \"com.redbubble\" %% \"finch-sangria\" % \"0.3.8\"\n```\n\n# Usage\n\n1. Configure the executor:\n\n    ```scala\n    val schema = ...           // your Sangria schema\n    val context = ...          // your root context\n    val errorReporter = ...    // a way to log errors, e.g. Rollbar\n    val serverMetrics = ...    // your stats receiver\n    val logger = ...           // a logger\n\n    val executor = GraphQlQueryExecutor.executor(\n      schema, context, maxQueryDepth = 10)(errorReporter, serverMetrics, logger)\n    ```\n\n  Set the max depth to whatever suits your schema (you'll likely need \u003e= 10 for the introspection query).\n\n1. Write your endpoint:\n\n    ```scala\n    import com.redbubble.graphql.GraphQlRequestDecoders.graphQlQueryDecode\n\n    object GraphQlApi {\n      val stats = StatsReceiver.stats\n\n      def graphQlGet: Endpoint[Json] =\n        get(\"graphql\" :: graphqlQuery) { query: GraphQlQuery =\u003e\n          executeQuery(query)\n        }\n\n      def graphQlPost: Endpoint[Json] =\n        post(\"graphql\" :: jsonBody[GraphQlQuery]) { query: GraphQlQuery =\u003e\n          executeQuery(query)\n        }\n\n      private def executeQuery(query: GraphQlQuery): Future[Output[Json]] = {\n        val operationName = query.operationName.getOrElse(\"unnamed_operation\")\n        stats.counter(\"count\", operationName).incr()\n        Stat.timeFuture(stats.stat(\"execution_time\", operationName)) {\n          runQuery(query)\n        }\n      }\n\n      private def runQuery(query: GraphQlQuery): Future[Output[Json]] = {\n        val result = executor.execute(query)(globalAsyncExecutionContext)\n\n        // Do our best to map the type of error back to a HTTP status code\n        result.map {\n          case SuccessfulGraphQlResult(json) =\u003e Output.payload(json, Status.Ok)\n          case ClientErrorGraphQlResult(json, _) =\u003e Output.payload(json, Status.BadRequest)\n          case BackendErrorGraphQlResult(json, _) =\u003e Output.payload(json, Status.InternalServerError)\n        }\n      }\n    }\n    ```\n\n1. Bring the response encoder into scope when you create your `Service`:\n\n    ```scala\n    import com.redbubble.graphql.GraphQlEncoders.graphQlResultEncode\n\n    val api = GraphQlApi.graphQlGet :+: GraphQlApi.graphQlPost\n    val service = api.toServiceAs[Application.Json]\n    Http.server.serve(\":8080\", service)\n    ```\n\n# GraphiQL\n\nIf you want to integrate [GraphiQL](https://github.com/graphql/graphiql) (you should), it's pretty easy.\n\n1. Pull down the latest [GraphiQL file](https://github.com/graphql/graphiql/blob/master/example/index.html).\n\n1. You may need to adjust the paths within the GraphiQL file if you're using versioned paths, etc.\n\n1. Stick it somewhere in your classpath.\n\n1. Write an endpoint for it:\n\n    ```scala\n    object ExploreApi {\n      private val graphiQlPath = \"/graphiql.html\"\n\n      def explore: Endpoint[Response] = get(\"explore\") {\n        classpathResource(graphiQlPath).map(fromStream) match {\n          case Some(content) =\u003e asyncHtmlResponse(Status.Ok, AsyncStream.fromReader(content, chunkSize = 512.kilobytes.inBytes.toInt))\n          case None =\u003e textResponse(Status.InternalServerError, Buf.Utf8(s\"Unable to find GraphiQL at '$graphiQlPath'\"))\n        }\n      }\n\n\t    private def classpathResource(name: String): Option[InputStream] = Option(getClass.getResourceAsStream(name))\n    }\n    ```\n\n# Other Fun Bits\n\nWe've added some other bits \u0026 pieces to make using Sangria easier.\n\n## Scalar types\n\nThere are various helpers that can help you define Scalar types. For example to add support for a tagged type:\n\n```scala\n//\n// Set up a tagged type\n//\n\nimport shapeless.tag\nimport shapeless.tag._\n\ntrait PixelWidthTag\ntype PixelWidth = Int @@ PixelWidthTag\ndef PixelWidth(w: Int): @@[Int, PixelWidthTag] = tag[PixelWidthTag](w)\n\n//\n// Define your GraphQL type for the tagged type\n//\n\nprivate val widthRange = 1 to MaxImageDimension\nprivate implicit val widthInput = new ScalarToInput[PixelWidth]\n\nprivate case object WidthCoercionViolation\n    extends ValueCoercionViolation(s\"Width in pixels, between ${widthRange.start} and ${widthRange.end}\")\n\nprivate def parseWidth(i: Int) = intValueFromInt(i, widthRange, PixelWidth, () =\u003e WidthCoercionViolation)\n\nval WidthType = intScalarType(\n  \"width\",\n  s\"The width of an image, in pixels, between ${widthRange.start} and ${widthRange.end} (default $DefaultImageWidth).\",\n  parseWidth, () =\u003e WidthCoercionViolation)\n\nval WidthArg: Argument[PixelWidth] = Argument(\n  name = \"width\",\n  argumentType = OptionInputType(WidthType),\n  description = s\"The width of an image, in pixels, between ${widthRange.start} and ${widthRange.end} (default $DefaultImageWidth).\", defaultValue = DefaultImageWidth)\n```\n\n## Input types\n\nWe've also added support for input types, in a similar way to how other types are handled, they are typesafe.\n\n```scala\n// Tagged type\ntrait PushNotificationTokenTag\ntype PushNotificationToken = String @@ PushNotificationTokenTag\ndef PushNotificationToken(t: String): @@[String, PushNotificationTokenTag] = tag[PushNotificationTokenTag](t)\n\n// GraphQL type\nprivate case object PushNotificationTokenCoercionViolation\n    extends ValueCoercionViolation(s\"Push notification token expected\")\n\nprivate def parseToken(s: String): Either[PushNotificationTokenCoercionViolation.type, PushNotificationToken] =\n  Right(PushNotificationToken(s))\n\nval PushNotificationTokenType =\n  stringScalarType(\n    \"PushNotificationToken\", s\"An iOS push notification token.\",\n    parseToken, () =\u003e PushNotificationTokenCoercionViolation\n  )\n\nval PushNotificationTokenArg =\n  Argument(\"token\", PushNotificationTokenType, description = s\"An iOS push notification token.\")\n\n\n//\n// Input type for our type\n//\nval FieldPushNotificationToken = InputField(\n  \"token\",\n  OptionInputType(PushNotificationTokenType),\n  \"If available, the push notification token for the device. May be empty if the user has not given permission to send notifications.\"\n)\n\nval RegisterDeviceType: InputObjectType[DefaultInput] =\n  InputObjectType(\n    name = \"RegisterDevice\",\n    description = \"Register device fields.\",\n    fields = List(FieldPushNotificationToken, FieldBundleId, FieldAppVersion, FieldOsVersion)\n  )\n\nval RegisterDeviceArg = Argument(InputFieldName, RegisterDeviceType, \"Register device fields.\")\n\n//\n// Let's use that type in a mutation\n//\n\nobject DeviceRegistration extends InputHelper {\n  def registerDevice(ctx: Context[RootContext, Unit]): Action[RootContext, RegisteredDevice] = {\n    val token = ctx.inputArg(FieldPushNotificationToken).flatten\n    val registeredDevice = for {\n      bundleId \u003c- ctx.inputArg(FieldBundleId)\n      appVersion \u003c- ctx.inputArg(FieldAppVersion).flatMap(fromRawVersion)\n      osVersion \u003c- ctx.inputArg(FieldOsVersion).flatMap(fromRawVersion)\n    } yield {\n      val device = Device.device(token, App(bundleId, appVersion), osVersion)\n      ctx.ctx.registerDevice(device)\n    }\n    registeredDevice.getOrElse(Future.exception(graphQlError(\"Unable to parse device input fields\"))).asScala\n  }\n}\n\nval MutationType: ObjectType[RootContext, Unit] = ObjectType(\n  \"MutationAPI\",\n  description = \"The Redbubble iOS Mutation API.\",\n  fields[RootContext, Unit](\n    Field(\n      name = \"registerDevice\",\n      arguments = List(RegisterDeviceArg),\n      fieldType = OptionType(RegisteredDeviceType),\n      resolve = registerDevice\n    )\n  )\n)\n```\n\n# Release\n\nFor contributors, a cheat sheet to making a new release:\n\n```shell\n$ git commit -m \"New things\" \u0026\u0026 git push\n$ git tag -a v0.0.3 -m \"v0.0.3\"\n$ git push --tags\n$ ./sbt publish\n```\n\n# Contributing\n\nIssues and pull requests are welcome. Code contributions should be aligned with the above scope to be included, and include unit tests.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fredbubble%2Ffinch-sangria","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fredbubble%2Ffinch-sangria","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fredbubble%2Ffinch-sangria/lists"}