【问题标题】:Graphql-ruby how to define a hash as typeGraphql-ruby 如何将哈希定义为类型
【发布时间】:2020-09-16 03:02:10
【问题描述】:

是否有可能在 graphql-ruby 模式中将 Hash 定义为 Type 字段? 在我的数据结构中有一个多语言字符串类型,它由作为键的语言代码和相应的文本组成。目前提供了 2 种语言,例如:

{ 
  "en" : "hello",
  "de" : "hallo"
}

所以构建一个这样的类型就足够了:

 class Types::LanguageStringType < GraphQL::Schema::Object
   field :de, String, null:true
   field :en, String, null:true
 end

提供 String 到 String 的 Map 的类型是什么样子的?对应的 typescript 界面如下所示:

title: {
  [language: string]: string;
}

更进一步,比如递归节点:

export interface NodeDescription {
  name: string
  children?: {
      [childrenCategory: string]: NodeDescription[];
  }
}

有没有办法在字段中使用它作为 graphql-ruby 架构中的 Types::NodeDescriptionType?

【问题讨论】:

    标签: ruby-on-rails ruby graphql graphql-ruby graphql-schema


    【解决方案1】:

    没有通用对象类型这样的东西。并且没有内置的 String -> String Hash 类型。您的 GraphQL API 建立在您必须提前定义的特定对象图之上。如果你想要的只是一个字符串 -> 字符串哈希,那么你可以定义你自己的标量,或者如果它足够你可以使用 graphql-ruby 附带的内置 JSON 标量:

    来源:https://graphql-ruby.org/type_definitions/scalars.html

    【讨论】:

    • 感谢您的回答!我想将我的架构转储到schema.json 中,并使用此文件生成带有graphql-code-gen 的打字稿接口。如果有自定义标量类型,是否可以生成类似于NodeDescription 的 Typescript 接口?我的感觉是不可能的:/
    • 我不熟悉graphql-code-gen,但它可能是可能的。我搜索了“graphql-code-gen custom scalars”,发现一些结果或多或少像你想要做的。
    猜你喜欢
    • 2017-02-22
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    • 2011-12-19
    • 2016-12-29
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多