You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Scala Sangria导出JSON格式GraphQL Schema适配apollo-codegen?

我刚好处理过类似的场景,给你两个实用的解决方案,不管是直接在代码里生成,还是通过SBT自动构建,都能搞定:

方法一:让Sangria直接生成JSON格式的Schema

Sangria本身提供了将Schema AST转换为JSON的工具类,配合对应的JSON库就能直接生成符合apollo-codegen要求的JSON格式。这里以Jackson为例(你也可以用Play JSON等其他实现):

  1. 首先添加对应JSON库的Sangria绑定依赖到你的build.sbt:
libraryDependencies += "org.sangria-graphql" %% "sangria-json-jackson" % "3.0.0" // 版本号请匹配你的Sangria版本
  1. 在代码中生成并写入JSON Schema:
import sangria.schema.Schema
import sangria.ast.AstToJson
import sangria.json.jackson._ // 导入Jackson的JSON绑定
import java.nio.file.{Files, Paths}

// 替换成你自己的Schema实例
val yourGraphQLSchema: Schema[_, _] = YourSchemaDefinition.schema

// 将Schema AST转换为格式化的JSON字符串
val schemaJson = AstToJson.convert(yourGraphQLSchema.toAst, prettyPrint = true)

// 写入到指定文件,比如resources目录
Files.write(Paths.get("src/main/resources/graphql/schema.json"), schemaJson.getBytes)

这样生成的JSON文件就能直接被apollo-codegen使用了。如果用Play JSON的话,只需要把依赖换成sangria-json-play,导入换成sangria.json.play._即可。

方法二:通过SBT任务自动生成JSON Schema

如果想把Schema生成集成到构建流程里,不用手动跑代码,可以写一个SBT任务,每次编译前自动生成JSON文件:

在你的build.sbt中添加以下配置:

// 添加JSON绑定依赖
libraryDependencies += "org.sangria-graphql" %% "sangria-json-jackson" % "3.0.0" % "compile"

// 定义生成JSON Schema的任务
val generateGraphQLSchemaJson = taskKey[Unit]("Generates GraphQL Schema in JSON format for Apollo Codegen")

generateGraphQLSchemaJson := {
  import sangria.schema.Schema
  import sangria.ast.AstToJson
  import sangria.json.jackson._
  import java.nio.file.{Files, Paths}

  // 引用你的Schema实例(需替换成实际的包路径和对象)
  val schema = com.yourcompany.graphql.YourSchema.schema

  val schemaJson = AstToJson.convert(schema.toAst, prettyPrint = true)
  val outputPath = Paths.get("src/main/resources/graphql/schema.json")

  // 确保目录存在
  Files.createDirectories(outputPath.getParent)
  Files.write(outputPath, schemaJson.getBytes)
  println(s"✅ Generated JSON Schema at: ${outputPath.toAbsolutePath}")
}

// 让编译任务依赖这个生成任务,每次编译前自动执行
compile in Compile := (compile in Compile).dependsOn(generateGraphQLSchemaJson).value

这样每次执行sbt compile的时候,都会自动生成最新的JSON Schema文件,完全不用手动干预。

额外提示

如果你的apollo-codegen版本较新,其实也支持直接使用SDL格式(就是schema.renderPretty生成的字符串)作为输入,你可以试试直接把renderPretty的输出写入.graphql文件,然后在apollo-codegen命令中指定这个文件,可能更简单。不过如果确实需要JSON格式,上面的两种方法都能完美解决问题。

内容的提问来源于stack exchange,提问作者Oleg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:25:49