5

刚开始学习理性反应,并与尝试读取 ENUM 值的 graphql 设置作斗争。

设置

  • 理性反应
  • 阿波罗graphql
  • graphql_ppx
  • github graphql 端点

我正在通过 github api 获取最新的拉取请求数据并读取status作为枚举并在 gql 文档中定义为的属性:

  • 打开
  • 关闭
  • 合并

检查网络选项卡,我看到状态是作为字符串接收的。在应用程序中,当我记录字段时,我得到一堆反映值的整数。smb 可以解释一下,我如何将数据作为字符串“打印”到我的视图中,以及为什么将它们转换为整数?是否有某种生成的类型可以用于变体开关?

let stateEnum = data->map(node => node##state);
Js.log(stateEnum) // possible values: 880069578, 982149804 or -1059826260
// somehow switch these values here?! :)
// current type of `stateEnum` is option('a)

非常感谢您,祝您有美好的一天!

4

2 回答 2

4

GraphQL 枚举表示为 Reason 多态变体。在引擎盖下,在运行时,它们只是整数。如果您想将它们显示给用户,您有两个选择: 1. 使用开关手动将它们映射到字符串

let status = 
  switch(node#status) {
    | `OPEN => “Open”
    // other cases
  }
  1. 您可以使用 BuckleScript 功能生成 jsConverters:
[@bs.deriving jsConverter]
type status = [ |`OPEN | `CLOSED /* other cases */]

这将为您生成两个函数:statusToJsstatusFromJs. 它们帮助您将变体转换为字符串和从字符串转换。

这是关于它的 BuckleScript 文档:https ://bucklescript.github.io/docs/en/generate-converters-accessors#convert-between-js-string-enum-and-bs-polymorphic-variant

于 2019-07-12T20:05:36.920 回答
1

正如@Herku 在他的评论中提到的那样,关键是要做到这一点:

// asume that your enum is on a gqp property called `state`
// and we use the built in lib `Belt.Option` and the fn `getWithDefault`
// this way we are sure, that `stateEnum` is defined with one of the valid enum values
let stateEnum = data->map(node => node##state)->getWithDefault(`OPEN);

// next we switch the polymorphic variant
let state = switch(stateEnum) {
 | `OPEN => "open"
 | `CLOSED => "close"
 | `MERGED` => "merged"
}

// str = let str = ReasonReact.string;
str(state);
于 2019-07-12T20:09:22.833 回答