|
2 | 2 |
|
3 | 3 | namespace ChrisWhite\B2; |
4 | 4 |
|
| 5 | +use ChrisWhite\B2\Exceptions\CacheException; |
5 | 6 | use ChrisWhite\B2\Exceptions\NotFoundException; |
6 | 7 | use ChrisWhite\B2\Exceptions\ValidationException; |
7 | 8 | use ChrisWhite\B2\Http\Client as HttpClient; |
| 9 | +use Illuminate\Cache\CacheManager; |
| 10 | +use Illuminate\Container\Container; |
| 11 | +use Illuminate\Filesystem\Filesystem; |
8 | 12 |
|
9 | 13 | class Client |
10 | 14 | { |
11 | 15 | protected $accountId; |
12 | 16 | protected $applicationKey; |
| 17 | + protected $cache; |
13 | 18 |
|
14 | 19 | protected $authToken; |
15 | 20 | protected $apiUrl; |
@@ -45,9 +50,34 @@ public function __construct($accountId, $applicationKey, array $options = []) |
45 | 50 | $this->client = new HttpClient(['exceptions' => false]); |
46 | 51 | } |
47 | 52 |
|
| 53 | + // initialize cache |
| 54 | + $this->createCacheContainer(); |
| 55 | + |
48 | 56 | $this->authorizeAccount(); |
49 | 57 | } |
50 | 58 |
|
| 59 | + private function createCacheContainer() |
| 60 | + { |
| 61 | + $container = new Container; |
| 62 | + $container['config'] = [ |
| 63 | + 'cache.default' => 'file', |
| 64 | + 'cache.stores.file' => [ |
| 65 | + 'driver' => 'file', |
| 66 | + 'path' => __DIR__ . '/Cache', |
| 67 | + ], |
| 68 | + ]; |
| 69 | + $container['files'] = new Filesystem; |
| 70 | + |
| 71 | + try { |
| 72 | + $cacheManager = new CacheManager($container); |
| 73 | + $this->cache = $cacheManager->store(); |
| 74 | + } catch (\Exception $e) { |
| 75 | + throw new CacheException( |
| 76 | + $e->getMessage() |
| 77 | + ); |
| 78 | + } |
| 79 | + } |
| 80 | + |
51 | 81 | /** |
52 | 82 | * Create a bucket with the given name and type. |
53 | 83 | * |
@@ -378,9 +408,15 @@ public function deleteFile(array $options) |
378 | 408 | */ |
379 | 409 | protected function authorizeAccount() |
380 | 410 | { |
381 | | - $response = $this->client->request('GET', 'https://api.backblazeb2.com/b2api/v1/b2_authorize_account', [ |
382 | | - 'auth' => [$this->accountId, $this->applicationKey], |
383 | | - ]); |
| 411 | + $client = $this->client; |
| 412 | + $accountId = $this->accountId; |
| 413 | + $applicationKey = $this->applicationKey; |
| 414 | + |
| 415 | + $response = $this->cache->remember('RunCloud-B2-SDK-Authorization', 60, function () use ($client, $accountId, $applicationKey) { |
| 416 | + return $client->request('GET', 'https://api.backblazeb2.com/b2api/v1/b2_authorize_account', [ |
| 417 | + 'auth' => [$accountId, $applicationKey], |
| 418 | + ]); |
| 419 | + }); |
384 | 420 |
|
385 | 421 | $this->authToken = $response['authorizationToken']; |
386 | 422 | $this->apiUrl = $response['apiUrl'] . '/b2api/v1'; |
|
0 commit comments