Commit 6562e8fc by Triyah Fatmawati

Fix guzzle `429 Too Many Requests` response

parent 06298898
......@@ -7,9 +7,13 @@
use App\Models\VPengusul;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use Storage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Session;
class SakuController extends Controller
......@@ -63,19 +67,68 @@ public function index(Request $request) {
}
public function getFileName($tahun, $nosurat){
$client = new Client();
$response = $client->request('GET', 'https://e-office.unesa.ac.id/api/show-surat-keluar/'.$tahun.'/'.$nosurat);
$data = json_decode($response->getBody(), true);
if (is_null($data)) {
// $client = new Client();
// $response = $client->request('GET', 'https://e-office.unesa.ac.id/api/show-surat-keluar/'.$tahun.'/'.$nosurat);
// $data = json_decode($response->getBody(), true);
// if (is_null($data)) {
// $namafile = '';
// }
// if (empty($data)) {
// $namafile = '';
// }
// else{
// $namafile = $data['namafile'];
// }
// return $namafile;
// Buat handler stack untuk Guzzle
$handlerStack = HandlerStack::create();
// Tambahkan retry middleware
$handlerStack->push(Middleware::retry(
function ($retries, $request, $response, $exception) {
// Maksimum 3 kali percobaan ulang
if ($retries >= 3) {
return false;
}
// Jika response 429 (Too Many Requests), retry
if ($response && $response->getStatusCode() == 429) {
return true;
}
return false;
},
function ($retries) {
// jeda 1s, 2s, 3s...
return 1000 * $retries;
}
));
// Inisialisasi client
$client = new Client([
'handler' => $handlerStack,
'timeout' => 10, // optional: timeout tiap request
]);
try {
$response = $client->request('GET', "https://e-office.unesa.ac.id/api/show-surat-keluar/{$tahun}/{$nosurat}");
$data = json_decode($response->getBody(), true);
if (empty($data) || is_null($data)) {
$namafile = '';
} else {
$namafile = $data['namafile'] ?? '';
}
} catch (RequestException $e) {
// Tangani jika gagal total (misal setelah 3 retry)
$namafile = '';
}
if (empty($data)) {
$namafile = '';
}
else{
$namafile = $data['namafile'];
// Opsional: tulis log error
Log::error("Gagal ambil surat keluar: ".$e->getMessage());
}
return $namafile;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment