Search code examples
androidapikotlingraphqlretrofit

Graphql get direct requested model


I implemented a sample of Graphql by Retrofit. I have a response like this:

                if (response.isSuccessful) {
                Log.e("response", response.body().toString())

Also, this is my interface class:

suspend fun postDynamicQuery(@Body body: String): Response<String>

Now I want to change my method by giving a direct model. this is the servers' answer.

{
"data": {
    "getCityByName": {
        "id": "112931",
        "name": "Tehran",
        "country": "IR",
        "coord": {
            "lon": 51.4215,
            "lat": 35.6944
        }
    }
}

To give a model answer, I should have a model like this:

data class CityModel(
    val data: Data
)

data class Data(
    val getCityByName: GetCityByName
)

data class GetCityByName(
    val id: String,
    val name: String,
    val country: String,
    val coord: Coord
)

data class Coord(
    val lon: Double,
    val lat: Double
)

And these two changes:

                if (response.isSuccessful) {
                cityModel = response.body()}

and

suspend fun postDynamicQuery(@Body body: String): Response<CityModel>

PROBLEM: I want a city model without creating a Data model and a CityModel model. this is a boilerplate to make two extra models for each API.

  • I used GsonConverterFactory for converting to model:

          .addConverterFactory(ScalarsConverterFactory.create())
          .addConverterFactory(GsonConverterFactory.create())
    

Solution

  • I searched for solving this problem. The only way is using the Appolo library.
    It has some benefits that I'll mention.

    1. Type-safety: All models are created automatically by the schema. Also, you can use the models in your application.
    2. Less-code: this library provides some code via using the GraphQL schematic.
    3. Error-free: your queries and model are created automatically by the schematic, and as a result, you don't have any mistakes.
    4. Some tools provided for you IDE for easy using GraphQL tools

    For adding this library you need to add these dependencies on your build.gradle file.

        implementation("com.apollographql.apollo3:apollo-runtime:3.3.2")
        implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.5.0'