Hello, I have a question due to my beginner level ...
# apollo-kotlin
g
Hello, I have a question due to my beginner level in GraphQL and Apollo-Client in Kotlin. Why do the types used in a request only generate code within the scope of that request? For example, if an address type is defined only once in my schema but used multiple times in a request or in multiple requests, this address will generate as many address types as its usage in the requests. This multiple generation prevents sharing code such as function extensions. Can we generate code that shares the types used in the requests?
a
You probably want fragments, they will generate the same thing every time you use them: https://www.apollographql.com/docs/kotlin/essentials/fragments/
๐Ÿ˜… 1
๐Ÿ‘ 1
g
Thanks a lot!
a
๐Ÿ‘ I ran into the exact same thing when we started using Apollo, until I realized fragments was a thing ๐Ÿ˜„
w
And to elaborate, in GraphQL you're not exactly fetching a type, but a selection over that type. Even if you fetch the same fields of a given type in different queries, Apollo can't assume they'll always stay the same, so it has to generate unique types for them. Imagine a type
type Bar { foo, bar, baz }
and in two queries you fetch
bar { foo, bar }
. What would happen if Apollo generated common type and then you decided to also fetch
baz
but only in one of those queries? Or no longer fetch
foo
also in just one of those two queries? And fragments are exactly the mechanism that indicates to Apollo that you're always fetching exactly the same fields, so generating a common type is possible. Because when you modify a fragment, it applies to all queries that use it
๐Ÿ‘Œ 2
โ˜๏ธ 1
b
If you want more context: @mbonnin wrote about this (and more) in this blog post ๐Ÿ™‚
๐Ÿ‘ 1
g
Thanks a lot for the detailed response @wasyl. I scratched the idea with the first response from @annsofi but your message makes it more clear.