Ahmed Majid
Ahmed Majid

Follow

Ahmed Majid

Follow
Using Django DateField with Apollo GraphQl in Android

Using Django DateField with Apollo GraphQl in Android

Ahmed Majid's photo
Ahmed Majid
ยทJul 25, 2021ยท

1 min read

Hello,

If you use Qraphql with Django (Graphene) and you have a model that contains DateField then when you have an android client that use Apollo to parse the graphql you will have a parse error with date field and you will not get the data that you want.

to fix this its very easy to use custom type scaler in apollo client:

first you gonna need to add these lines in your app gradle file into the end of it

apollo {
    customTypeMapping = [
            "Date" : "java.time.LocalDate"
    ]
}

Then update your apollo client class by adding these lines to it:

var dateCustomTypeAdapter = object : CustomTypeAdapter<LocalDate> {
    override fun decode(value: CustomTypeValue<*>): LocalDate {
        try {
            return LocalDate.parse(value.value.toString())
        } catch (e: ParseException) {
            throw RuntimeException(e)
        }

    }

    override fun encode(value: LocalDate): CustomTypeValue<*> {
        return CustomTypeValue.GraphQLString(Settings.System.DATE_FORMAT.format(value))
    }
}

var okhttpClient = OkHttpClient.Builder()
    .build()

var apolloClient = ApolloClient.builder()
    .serverUrl("SERVER_BASEURL")
    .okHttpClient(okhttpClient)
    .addCustomTypeAdapter(CustomType.DATE, dateCustomTypeAdapter)
    .build()

Thats it ๐Ÿ™‚

if you have any questions im glad to answer it in the comments below ๐Ÿ™‚

ย 
Share this