Skip to content

Instantly share code, notes, and snippets.

@mahendranv
Created May 16, 2021 14:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mahendranv/2fda2eb9ddba242a78ff675ba9b0cda4 to your computer and use it in GitHub Desktop.
Save mahendranv/2fda2eb9ddba242a78ff675ba9b0cda4 to your computer and use it in GitHub Desktop.
Setup to convert timestamp to DateTime in GraphQL
apollo {
generateKotlinModels.set(true)
customTypeMapping = [
"timestamptz" : "org.threeten.bp.LocalDateTime"
]
}
dependencies {
implementation "org.threeten:threetenbp:1.5.1"
}
/**
* Timestamp delivered as string from API. This adapter takes care of encode / decode the same.
*/
private val timeStampAdapter = object : CustomTypeAdapter<LocalDateTime> {
private val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSz")
override fun decode(value: CustomTypeValue<*>): LocalDateTime {
return try {
LocalDateTime.parse(value.value.toString(), formatter)
} catch (e: Exception) {
throw RuntimeException("Cannot parse date: ${value.value}")
}
}
override fun encode(value: LocalDateTime): CustomTypeValue<*> {
return try {
CustomTypeValue.GraphQLString(formatter.format(value))
} catch (e: Exception) {
throw RuntimeException("Cannot serialize the date date: ${value}")
}
}
}
val apolloClient = ApolloClient
.builder()
.serverUrl("// url //")
.addCustomTypeAdapter(CustomType.TIMESTAMPTZ, timeStampAdapter)
.build()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment