Skip to main content
4 of 4
added 486 characters in body

Extend API V1/products to put the not available products at the end

I want to display out of stock products at the end of the V1/products response.

So far I tried to create a plugin on Magento\Catalog\Api\ProductRepositoryInterface to override the getList method but it doesn't work.

I don't know if this is a good method or I have to use an Observer or a plugin on another Class

I tried this in a di.xml file :

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Catalog\Api\ProductRepositoryInterface">
        <plugin name="products-list" type="Custom\Api\Plugin\ProductList"/>
    </type>
</config>

And in ProductList.php :

<?php

namespace Custom\Api\Plugin;

class ProductGet
{

    public function __construct(
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $collectionFactory
    ) {
        $this->collectionFactory = $collectionFactory;
    }

    public function getList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria)
    {
        // this method isn't called :(
    }
}

Update #1 I added a beforeGetList function :

public function beforeGetList(
        ProductRepositoryInterface $subject,
        SearchCriteriaInterface $searchCriteria
    ) {
        $sortOrders = $searchCriteria->getSortOrders() ?? array();
        $sortOrders[] = $this->sortOrderBuilder->setField('stock_status')->setDirection(SortOrder::SORT_DESC)->create();
        $searchCriteria->setSortOrders($sortOrders);
        return [$searchCriteria];
    }