I am developing a Laravel project from the beginning, and I want to create a generic class that can queue a job for data to be pushed to an external API. How can I do that? I am new to queues and jobs.
Following Code is what I tried. I created the following Job class and called it where I need to push data to external APIs. This worked for me. But I am open to other solutions.
class ApiPushService implements ShouldQueue
{
use InteractsWithQueue, SerializesModels, Queueable;
protected $endpoint;
protected $data;
/**
* ApiPushService constructor.
* @param $endpoint
* @param $data
*/
public function __construct($endpoint, $data)
{
$this->endpoint = $endpoint;
$this->data = $data;
}
/**
* @param Client $guzzleClient
*/
public function handle(Client $guzzleClient)
{
//get external api url
$url = $this->endpoint;
try {
$response = $guzzleClient->request('POST', $url, [
'headers' => array("Content-Type" => "application/json"),
'json' => $this->data
]);
} catch (BadResponseException $e) {
Log::error("ApiPushService (handle): Guzzle Bad Response Exception : " . $e->getMessage());
} catch (RequestException $e) {
Log::error("ApiPushService (handle): Guzzle Request Exception : " . $e->getMessage());
} catch (GuzzleException $e) {
Log::error("ApiPushService (handle): Guzzle Exception : " . $e->getMessage());
}
if ($response->getStatusCode() != 200) {
Log::info("ApiPushService (handle): Endpoint Response : ",
json_decode((string)$response->getBody(), true));
} else {
Log::error("ApiPushService (handle): Guzzle Request error : ",
json_decode((string)$response->getBody(), true));
}
}
}