Created
May 16, 2021 14:29
-
-
Save mahendranv/2fda2eb9ddba242a78ff675ba9b0cda4 to your computer and use it in GitHub Desktop.
Setup to convert timestamp to DateTime in GraphQL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
apollo { | |
generateKotlinModels.set(true) | |
customTypeMapping = [ | |
"timestamptz" : "org.threeten.bp.LocalDateTime" | |
] | |
} | |
dependencies { | |
implementation "org.threeten:threetenbp:1.5.1" | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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