Search code examples
androidkotlinapolloapollo-kotlingraphql-fragments

Fragments with Apollo kotlin Graphql not getting Fragment type in response using Moshi Converter


When using a Fragment in my query for Graphql call, I am facing below issue with Fragment during Moshi conversion.

I have query like this

fetchData($userId: String!) 
{
  ...UserDataFields
}
fragment UserDataFields on UserData {
id,
name,
profileImage
}

When I make Api call and copy the response from Android logcat, convert it to json file and use that with Moshi converter in my unit tests to mock the response, I see the response does not include UserDataFields, it has below:

{
"data": {
"fetchData": {
  "__typename": "UserData",
  "id": "23455",
  "name": "example",
  "profile": {
   ....
   }
 }
}

But my kotlin generated types has

Data(
public val fetchData: FetchData?
):Query.Data

FetchData(
public val __typename: String,
public val userDataFields: UserDataFields
)

UserDataFields(
public val id: String,
public val name: String,
public val profile: Profile,
): Fragment.Data

It is looking for the UserDataFields data inside the response json but I am getting the properties directly in response without being nested inside UserDataFields.

Here is the Moshi Conversion code:

val mockResponse = typeFromLocalJson<UserDetailsSearchQuery.Data>(
"my json response file path",
Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
).getOrhandle {throw it }

It is not throwing an exception, it is looking for UserDataFields property inside fetchData..which is not available in the json, Hence returning null.

Can someone please help me fix this, thanks in advance.


Solution

  • When using fragments, it is expected that the shape of the generated model is different from the shape of the JSON payloads.

    In the generated models, each fragment has its own field, whereas in JSON the fragment's fields are embedded in the main object.

    Because of this you cannot serialize the generated models into JSON via Moshi and expect the generated parser to be able to read them.

    Instead, you can serialize them using the Apollo generated adapters, which knows how to handle these fragment fields, using operation.composeJsonResponse() (see the doc).

    Alternatively for your tests you could use the TestNetworkTransport.