【问题标题】:Destructure a JsonObject to a GraphQL Type on Return返回时将 JsonObject 解构为 GraphQL 类型
【发布时间】:2021-08-05 13:33:27
【问题描述】:

Vertx 是 json 作为一等公民的忠实拥护者,我也是它的忠实拥护者。我将 jsonb 列存储在 postgres 作为我的主要数据存储机制。有点像这样:

CREATE TABLE game (
    id varchar(16) not null default next_id() primary key,
    data jsonb not null
);

然后我检索数据、处理 json 对象并将其返回给浏览器。效果很好。

不过,我也在尝试使用 GraphQL,但似乎我无法将 json 对象转换为 graphql 类型。例如我将此数据存储在数据库中:

{"name": "dominion", "createdBy": "Donald X. Vaccarino", "id": 233}

这是 graphql 类型:

type Game {
    id: Long,
    name: String,
    createdBy: String,
    createdAt: DateTime,
    deletedAt: DateTime
}

这个 graphql 查询返回一个空项目列表,因为 jsonArray 中的 jsonObject(游戏)没有被分解为 Game 类型:

type Query {
    allGames(secureOnly: Boolean = false): [Game]
}

但如果我使用 json 作为查询结果类型,游戏列表确实会显示:

type Query {
    allGames(secureOnly: Boolean = false): [JSON]
}

不过,问题在于 graphql 模式中现在没有类型信息。没有办法让客户端知道JSON对象中有哪些属性

我的数据获取器有这种类型:

DataFetcher[CompletionStage[JsonArray]]

关于如何在代码中返回 json 并让 graphql 响应返回游戏类型有什么想法吗?

【问题讨论】:

  • @andrewjames,谢谢你的关注。我正在从原始形式更改一些代码,但也忘了更改那个地方

标签: java json scala graphql vert.x


【解决方案1】:

默认的 GraphQL 数据提取器是 PropertyDataFetcher

如果要支持 Vert.x JsonObjectJsonArray,则必须将 GraphQL-Java 配置为使用 VertxPropertyDataFetcher:

RuntimeWiring.Builder builder = RuntimeWiring.newRuntimeWiring();
builder.wiringFactory(new WiringFactory() {
  @Override
  public DataFetcher<Object> getDefaultDataFetcher(FieldWiringEnvironment environment) {
    return VertxPropertyDataFetcher.create(environment.getFieldDefinition().getName());
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-09
    • 2020-03-05
    • 1970-01-01
    相关资源
    最近更新 更多