Handling Interfaces in Resolvers
Interfaces can be used inside the GraphQL resolvers as well to resolve their fields dynamically based on a specific condition or the concrete type of the return object. Let’s look at a simplified example below –
In the below interface example, we have an interface Shape, with a findArea field inside it. We have 2 types derived from the interface, namely “Circle” and “Square”.
interface Shape {
findArea: Float!
}
type Circle implements Shape {
radius: Float!
findArea: Float!
}
type Square implements Shape {
length: Float!
findArea: Float!
}
Now, while defining the resolvers for the “findArea” field, we will define “__resolveType” function on the Shape interface, and based on the availability of specific fields inside the type, like “radius” or “length”, we will define the resolvers for the “findArea” for each of the concrete types, “Circle” and “Square”.
const resolvers = {
Shape: {
__resolveType(shape) {
if (shape.radius) {
return 'Circle';
}
if (shape.length) {
return 'Square';
}
return null;
},
},
Circle: {
findArea(circle) {
return Math.PI * circle.radius * circle.radius;
},
},
Square: {
findArea(square) {
return square.length * square.length;
},
},
};
Interfaces in GraphQL Schema
GraphQL is a powerful open-source query language for APIs. It is known for its flexibility and efficiency in fetching data from server endpoints. Unlike traditional REST APIs, which often have multiple endpoints for different resources, GraphQL typically exposes a single endpoint that allows clients to request exactly the data they need.
Interfaces in GraphQL help create a common set of fields and types that can be reused by other types or Queries. In this article, we will learn about the interfaces in GraphQL Schema.