DEV Community

Mahaveer
Mahaveer

Posted on

Can someone #ExplainLikeImFive - GraphQL Interfaces

Where exactly do we need to use Interfaces? I understand how to define and use them but can't develop an intuition on why would I need them :thinking_face:

Top comments (1)

Collapse
 
nestedsoftware profile image
Nested Software • Edited

I hope someone with more experience in GraphQL will chime in, but I'll share my impressions for now.

If you want to return several kinds of things to the client which share a core group of attributes, you may want to use interfaces (it looks as though union types may also be an option, depending on what you want to do).

I think this is probably most appropriate if the client doesn't always care about the details of each type and just wants to work with the generic attributes they all have in common. However, in some places, the client may want to look more closely at a result object and its specific attributes, ones that are not shared by the other types that implement the interface. In that case, the client can still do so.

I found this article, which seems as though it could be helpful. It's using ruby for graphql on the server-side, so if you're using something else, the syntax may be slightly different. They use the example of returning different kinds of instruments. If an instrument is a string-instrument, like a guitar, or violin, there is a specific field that stores the numberOfStrings for that instrument. The generic InstrumentInterface doesn't know about numberOfStrings, but the StringInstrument type, which implements this interface, adds this as an additional field.