【问题标题】:Use DateTime scalar in GraphQL queries and mutation on Android在 Android 上的 GraphQL 查询和变异中使用 DateTime 标量
【发布时间】:2022-02-03 17:22:10
【问题描述】:

我正在使用 GraphQL。架构包含:

scalar DateTime
type Something {
    timestamp: DateTime
}

当我构建应用程序时,ApolloClient 插件会生成类:

public class DateTime {
  public companion object {
    public val type: CustomScalarType = CustomScalarType("DateTime", "kotlin.Any")
  }
}

我在构建 ApolloClient 时必须使用这个吗?像这样?

val apolloClient = ApolloClient.builder()
    .serverUrl("xxxx")
    .okHttpClient(httpClient)
    .addCustomTypeAdapter(DateTime.type, adapter)
    .build()

我找到了here 已经可用的适配器列表,但我找不到如何导入它们,而且它们似乎都不合适。

我必须定义自己的自定义适配器吗?

编辑 要导入它们,只需导入 com.apollographql.apollo3:apollo-adapters

【问题讨论】:

    标签: android datetime graphql


    【解决方案1】:

    我找到了解决方案。 一共有三个步骤。

    导入/创建适配器

    您可以从 apollo 导入库:

    implementation "com.apollographql.apollo3:apollo-adapters:${apollo_version}"
    

    然后使用DateAdapter 或自己创建适配器,可能遵循DateAdapter 的方式:

    
    /**
     * An [Adapter] that converts an ISO 8601 String like "2010-06-01T22:19:44.475Z" to/from
     * a java [Date]
     *
     * It requires Android Gradle plugin 4.0 or newer and [core library desugaring](https://developer.android.com/studio/write/java8-support#library-desugaring).
     */
    object DateAdapter : Adapter<Date> {
      override fun fromJson(reader: JsonReader, customScalarAdapters: CustomScalarAdapters): Date {
        return Date(Instant.parse(reader.nextString()!!).toEpochMilliseconds())
      }
    
      override fun toJson(writer: JsonWriter, customScalarAdapters: CustomScalarAdapters, value: Date) {
        writer.value(Instant.fromEpochMilliseconds(value.time).toString())
      }
    }
    

    使用适配器:

    val apolloClient = ApolloClient.builder()
        .serverUrl("xxxx")
        .okHttpClient(httpClient)
        .addCustomTypeAdapter(DateTime.type, DateAdapter())
        .build()
    

    更新 build.gradle

    在 build.gradle 中更新 apollo 部分:

    apollo {
        customTypeMapping['DateTime'] = "java.util.Date"
    }
    

    【讨论】:

      猜你喜欢
      • 2019-12-03
      • 2022-01-21
      • 2019-04-11
      • 2020-01-14
      • 2019-05-17
      • 2023-03-12
      • 2017-02-21
      • 2019-10-21
      • 2020-01-21
      相关资源
      最近更新 更多