I'm trying to load shopify products through cache and im using Redis::throttle to prevent rate limit in shopify. My problem is I put all the process of fetching in a Batch and it returns a negative no. of pending jobs.
and here's my approach
public function load(Request $request, Sample $sample) {
return DB::transaction(function () use ($sample) {
$batch = Bus::batch([])->dispatch();
$since_id = 0;
while ($since_id >= 0) {
$fetchedProducts = (new ShopifyProduct(
$sample->shopify_domain,
$sample->shopify_info['access_token'])
)
->getById($since_id)
->then(function ($data) {
return $data['products'];
}, function () {
return [];
})
->wait();
if (collect($fetchedProducts)->count() == 0) break;
$lastProduct = Arr::last($fetchedProducts);
$since_id = $lastProduct['id'];
collect($fetchedProducts)
->each(function ($shopifyProduct) use($merchant, &$batch) {
$batch->add(new CacheProducts($shopifyProduct, $sample));
});
}
return $this->okResponse(['batch_id' => $batch->id])
->header('Content-Type', 'application/vnd.api+json');
});
}
and here's the job
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
Redis::throttle("shopify-cache")->allow(30)->every(60)->block(70)->then(function () {
(new Metafield(
$this->merchant->shopify_domain,
$this->merchant->shopify_info['access_token']
)
)
->get($this->shopifyProduct['id'], 'products')
->then(function ($data) {
$this->shopifyProduct['metafields'] = $data['metafields'];
$cacheProducts = Cache::tags($this->merchant->name)->get('products') ?? [];
array_push($cacheProducts, $this->shopifyProduct);
Cache::tags($this->merchant->name)->put('products', $cacheProducts, now()->addHour());
}, function ($e) {
})
->wait();
}, function () {
return $this->release(10);
});
}
