I need to create GraphQL for newly added products.
Thanks in advance.
app/code/Custom/NewlyProductGraphQl/etc/schema.graphqls
type Query {
newlyCreatedProducts: [NewlyCreatedProducts] @resolver(class: "Custom\\NewlyProductGraphQl\\Model\\Resolver\\NewlyCreatedProducts")
}
type NewlyCreatedProducts {
entity_id: Int
name: String
sku: String
}
app/code/Custom/NewlyProductGraphQl/Model/Resolver/NewlyCreatedProducts.php
<?php
declare(strict_types=1);
namespace Custom\NewlyProductGraphQl\Model\Resolver;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Query\Resolver\Value;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\Framework\GraphQl\Query\Resolver\ValueFactory;
/**
* Class NewlyCreatedProducts
*/
class NewlyCreatedProducts implements ResolverInterface
{
/**
* @var CollectionFactory
*/
protected $productCollectionFactory;
/**
* @var Visibility
*/
protected $catalogProductVisibility;
/**
* @var ValueFactory
*/
protected $valueFactory;
/**
* @param CollectionFactory $productCollectionFactory
* @param Visibility $catalogProductVisibility
* @param ValueFactory $valueFactory
*/
public function __construct(
CollectionFactory $productCollectionFactory,
Visibility $catalogProductVisibility,
ValueFactory $valueFactory
)
{
$this->productCollectionFactory = $productCollectionFactory;
$this->catalogProductVisibility = $catalogProductVisibility;
$this->valueFactory = $valueFactory;
}
/**
* @param Field $field
* @param $context
* @param ResolveInfo $info
* @param array|null $value
* @param array|null $args
* @return Value|mixed
*/
public function resolve(
Field $field,
$context,
ResolveInfo $info,
array $value = null,
array $args = null
) {
$data = $this->getNewlyProductCollection();
$result = function () use ($data) {
return !empty($data) ? $data : [];
};
return $this->valueFactory->create($result);
}
/**
* @return array
*/
public function getNewlyProductCollection(): array
{
$productData = [];
$collection = $this->productCollectionFactory->create();
$collection->setVisibility($this->catalogProductVisibility->getVisibleInCatalogIds());
$collection = $collection->addStoreFilter()
->addAttributeToSelect('*')
->addAttributeToSort('created_at', 'desc')
->setPageSize(10)
->setCurPage(1);
foreach ($collection as $product) {
array_push($productData, $product->getData());
}
return $productData ?: [];
}
}
Query:
query{
newlyCreatedProducts{
entity_id
name
sku
}
}
Thanks.