|
3 | 3 | namespace Statikbe\Surveyhero\Http;
|
4 | 4 |
|
5 | 5 | use Carbon\Carbon;
|
| 6 | +use Illuminate\Support\Facades\Cache; |
6 | 7 | use Illuminate\Support\Facades\Http;
|
7 | 8 | use stdClass;
|
8 | 9 |
|
9 | 10 | class SurveyheroClient
|
10 | 11 | {
|
11 | 12 | const CACHE_LATEST_REQUEST_TIME_KEY = 'latest-surveyhero-api-request-time';
|
12 | 13 |
|
13 |
| - const REQUEST_RATE_LIMIT_WAIT_TIME = 60000; |
14 |
| - |
15 | 14 | public function getSurveys(): array
|
16 | 15 | {
|
17 | 16 | $responsesData = $this->fetchFromSurveyHero('surveys');
|
@@ -120,7 +119,7 @@ private function fetchFromSurveyHero(string $urlPath, array $queryStringArgs = [
|
120 | 119 | {
|
121 | 120 | $this->preventThrottle();
|
122 | 121 |
|
123 |
| - $response = Http::retry(3, 600) |
| 122 | + $response = Http::retry(3, 800) |
124 | 123 | ->withBasicAuth(config('surveyhero.api_username'), config('surveyhero.api_password'))
|
125 | 124 | ->get(config('surveyhero.api_url').$urlPath, $queryStringArgs);
|
126 | 125 |
|
@@ -176,14 +175,17 @@ private function deleteFromSurveyHero(string $urlPath, array $queryStringArgs =
|
176 | 175 | //Ensure sleep between requests
|
177 | 176 | private function preventThrottle(): void
|
178 | 177 | {
|
179 |
| - if (cache(self::CACHE_LATEST_REQUEST_TIME_KEY)) { |
180 |
| - usleep(self::REQUEST_RATE_LIMIT_WAIT_TIME); |
| 178 | + if (Cache::has(self::CACHE_LATEST_REQUEST_TIME_KEY)) { |
| 179 | + //usleep is in microseconds, 1000000 is 1s. |
| 180 | + //Surveyhero only allows 2 requests per second. |
| 181 | + $sleepTime = 1000000 - (Carbon::now()->getTimestampMs() - Cache::get(self::CACHE_LATEST_REQUEST_TIME_KEY)) * 1000; |
| 182 | + usleep($sleepTime); |
181 | 183 | }
|
182 | 184 | }
|
183 | 185 |
|
184 | 186 | //Set latest request time with 1s TTL
|
185 | 187 | private function updateThrottle(): void
|
186 | 188 | {
|
187 |
| - cache([self::CACHE_LATEST_REQUEST_TIME_KEY => now()->format('Y-m-d H:i:s.u')], 1); |
| 189 | + Cache::put(self::CACHE_LATEST_REQUEST_TIME_KEY, Carbon::now()->getTimestampMs(), 1); |
188 | 190 | }
|
189 | 191 | }
|
0 commit comments