A TypeResolver helps to decide which type a concrete value belongs to. This is needed for Interface.
For example imagine you have an Interface called DashboardOutputInterface which resolves back to a series of classes called BannerSlider, CategorySlider and ProductSlider. The type resolver is responsible for examining a runtime object and deciding what GraphqlObjectType should be used to represent it, and hence what data fetchers and fields will be invoked.
CompanyName/ModuleName/etc/schema.graphqls
type Query {
dashboard : [DashboardOutputInterface] @resolver( class: "CompanyName\\ModuleName\\Model\\Resolver\\Dashboard")
}
interface DashboardOutputInterface @typeResolver(class: "CompanyName\\ModuleName\\Model\\Resolver\\CustomTypeResolverComposite") {
block_id: Int @doc(description: "Block Id")
block_type: String @doc(description: "Block Type")
position: Int @doc(description: "Position")
}
type BannerSlider implements DashboardOutputInterface {
id: Int
image: String
}
type ProductSlider implements DashboardOutputInterface {
id: Int
products: [ProductInterface]
}
type CategorySlider implements DashboardOutputInterface {
id: Int
categories: [CategoryInterface]
}
CompanyName\ModuleName\Model\Resolver\CustomTypeResolverComposite
public function resolveType(array $data) : string
{
if (isset($data['block_type'])) {
if ($data['block_type'] == 'category_slider') {
return 'CategorySlider';
} elseif ($data['block_type'] == 'product_slider') {
return 'ProductSlider';
} elseif ($data['block_type'] == 'banner_slider') {
return 'BannerSlider';
}
}
throw new GraphQlInputException(
__('Concrete type for %1 not implemented', ['DashboardOutputInterface'])
);
}
Your query look like
query getDashboard {
dashboard {
block_id
block_type
position
__typename
...CategorySliderFragement
...ProductSliderFragement
...BannerSliderFragement
}
}
fragment CategorySliderFragement on CategorySlider {
id
categories {
id
name
}
}
fragment ProductSliderFragement on ProductSlider {
id
products {
id
name
}
}
fragment BannerSliderFragement on BannerSlider {
id
image
}