Skip to content

Magento 2 : How to create a graphql api for fetch the best seller product collection with arguments search and filter like in the product graphql?

I am trying to fetch Best seller product collections using graphql like the one below.

bestSellers (
        pageSize: Int = 20 @doc(description: "The maximum number of results to return at once. The default value is 20."),
        currentPage: Int = 1 @doc(description: "The page of results to return. The default value is 1.")
    ): [ProductInterface] 
    @resolver(class:"Module\Graphql\Model\Resolver\BestSeller")
    @doc(description:"Show the best selling items")
public function getBestSellerProducts()
    {
        $productDetails = [];
        $bestSellers = $this->_bestSellersCollectionFactory->create()
        ->setPeriod('year');

        foreach ($bestSellers as $bestSeller) {

            $product = $this->productRepository->getById($bestSeller->getProductId());
            $productData = $product->toArray();
            $productData['model'] = $product;
            $productDetails[] = $productData;
        }
        return $productDetails;
    }
}

How can I fetch these products using the same search and filter etc arguments used in the product graphql query (I want to filter these products using the available product attributes)?

 products (
        search: String @doc(description: "One or more keywords to use in a full-text search."),
        filter: ProductAttributeFilterInput @doc(description: "The product attributes to search for and return."),
        pageSize: Int = 20 @doc(description: "The maximum number of results to return at once. The default value is 20."),
        currentPage: Int = 1 @doc(description: "The page of results to return. The default value is 1."),
        sort: ProductAttributeSortInput @doc(description: "Specifies which attributes to sort on, and whether to return the results in ascending or descending order.")
    ): Products