From 4d26acea5bbdfbaf2cbbbf609b5dde7b578c40d5 Mon Sep 17 00:00:00 2001
From: Timothy J Warren <tim@timshomepage.net>
Date: Fri, 7 Dec 2018 10:24:42 -0500
Subject: [PATCH] Use the same API client instance across the codebase

---
 src/API/ParallelAPIRequest.php | 13 +++----------
 src/AnimeClient.php            | 21 +++++++++++++++++++--
 2 files changed, 22 insertions(+), 12 deletions(-)

diff --git a/src/API/ParallelAPIRequest.php b/src/API/ParallelAPIRequest.php
index 18ea2c91..355188b4 100644
--- a/src/API/ParallelAPIRequest.php
+++ b/src/API/ParallelAPIRequest.php
@@ -18,8 +18,7 @@ namespace Aviat\AnimeClient\API;
 
 use function Amp\call;
 use function Amp\Promise\{all, wait};
-
-use Amp\Artax\{Client, DefaultClient};
+use function Aviat\AnimeClient\getApiClient;
 
 /**
  * Class to simplify making and validating simultaneous requests
@@ -72,10 +71,7 @@ final class ParallelAPIRequest {
 	 */
 	public function makeRequests(): array
 	{
-		$client = new DefaultClient();
-
-		// Timeouts suck
-		$client->setOption(Client::OP_TRANSFER_TIMEOUT, 0);
+		$client = getApiClient();
 
 		$promises = [];
 
@@ -98,10 +94,7 @@ final class ParallelAPIRequest {
 	 */
 	public function getResponses(): array
 	{
-		$client = new DefaultClient();
-
-		// Timeouts suck
-		$client->setOption(Client::OP_TRANSFER_TIMEOUT, 0);
+		$client = getApiClient();
 
 		$promises = [];
 
diff --git a/src/AnimeClient.php b/src/AnimeClient.php
index 55f1eb81..4440f5b0 100644
--- a/src/AnimeClient.php
+++ b/src/AnimeClient.php
@@ -207,6 +207,24 @@ function checkFolderPermissions(ConfigInterface $config): array
 	return $errors;
 }
 
+/**
+ * Get an API Client, with better defaults
+ *
+ * @return DefaultClient
+ */
+function getApiClient ()
+{
+	static $client;
+
+	if ($client === NULL)
+	{
+		$client = new DefaultClient;
+		$client->setOption(Client::OP_TRANSFER_TIMEOUT, 0);
+	}
+
+	return $client;
+}
+
 /**
  * Simplify making a request with Artax
  *
@@ -216,8 +234,7 @@ function checkFolderPermissions(ConfigInterface $config): array
  */
 function getResponse ($request): Response
 {
-	$client = new DefaultClient;
-	$client->setOption(Client::OP_TRANSFER_TIMEOUT, 0);
+	$client = getApiClient();
 	return wait($client->request($request));
 }