reindex after post api magento 2 code example

Example 1: reindex after post api magento 2

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $indexerCollectionFactory = $objectManager->get("\Magento\Indexer\Model\Indexer\CollectionFactory");
    $indexerFactory = $objectManager->get("\Magento\Indexer\Model\IndexerFactory");

    $indexerCollection = $indexerCollectionFactory->create();
    $allIds = $indexerCollection->getAllIds();
    foreach ($allIds as $id) {
        $indexer = $indexerFactory->create()->load($id);
        $indexer->reindexAll();
    }

Example 2: reindex after post api magento 2

<?php

namespace Sark\CustomApi\Model;

class CustomRepository implements Sark\CustomApi\Api\CustomRepositoryInterface
{
    /**
     * @var \Magento\Framework\Indexer\IndexerRegistry
     */
    private $indexerRegistry;
    /**
     * @var \Magento\Indexer\Model\ResourceModel\Indexer\State\CollectionFactory
     */
    private $stateCollectionFactory;

    public function __construct(
        \Magento\Framework\Indexer\IndexerRegistry $indexerRegistry,
        \Magento\Indexer\Model\ResourceModel\Indexer\State\CollectionFactory $stateCollectionFactory
    ) {
        $this->indexerRegistry = $indexerRegistry;
        $this->stateCollectionFactory = $stateCollectionFactory;
    }

    public function create()
    {
        $indexerStates = $this->stateCollectionFactory->create();
        foreach ($indexerStates->getItems() as $indexerState) {
            $indexerState->getIndexerId();
            $indexer = $this->indexerRegistry->get($indexerState->getIndexerId());
            if ($indexer->getId() && !$indexer->isWorking()) {
                $indexer->setScheduled(true);
            }
        }
    }
}

Tags:

Misc Example