Creating a route that makes a call from the server to an external service which is firewalled, with data sent back to the caller (like a ReactJS component)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Drupal\harlib_search\Controller; | |
use Drupal\Core\Controller\ControllerBase; | |
use GuzzleHttp\Client; | |
use Psr\Log\LoggerInterface; | |
use Symfony\Component\DependencyInjection\ContainerInterface; | |
use Symfony\Component\HttpFoundation\RequestStack; | |
use GuzzleHttp\Exception\RequestException; | |
use Symfony\Component\HttpFoundation\Response; | |
/** | |
* Class SearchController. | |
* | |
* @package Drupal\harlib_search\Controller | |
*/ | |
class SearchController extends ControllerBase { | |
/** | |
* The base url to do searches against. | |
* | |
* @var string | |
*/ | |
protected $baseSearchUrl = "http://YOUR_ENDPOINT_HERE"; | |
/** | |
* Symfony\Component\HttpFoundation\RequestStack definition. | |
* | |
* @var \Symfony\Component\HttpFoundation\RequestStack | |
*/ | |
protected $requestStack; | |
/** | |
* GuzzleHttp\Client definition. | |
* | |
* @var \GuzzleHttp\Client | |
*/ | |
protected $httpClient; | |
/** | |
* Psr\Log\LoggerInterface definition. | |
* | |
* @var \Psr\Log\LoggerInterface | |
*/ | |
protected $logger; | |
/** | |
* Constructor for our class. | |
*/ | |
public function __construct(RequestStack $request_stack, Client $http_client, LoggerInterface $logger) { | |
$this->requestStack = $request_stack; | |
$this->httpClient = $http_client; | |
$this->logger = $logger; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public static function create(ContainerInterface $container) { | |
return new static( | |
$container->get('request_stack'), | |
$container->get('http_client'), | |
$container->get('logger.factory')->get('harlib_search') | |
); | |
} | |
/** | |
* Controller action. Show the ReactJS component. | |
*/ | |
public function index() { | |
return [ | |
'#theme' => 'harlib_search', | |
]; | |
} | |
/** | |
* Fetch results from Hollis. | |
* | |
* @return \Symfony\Component\HttpFoundation\Response | |
* A Symfony response object. | |
*/ | |
public function results() { | |
$data = ''; | |
$uri = $this->baseSearchUrl . $this->requestStack->getCurrentRequest()->getQueryString(); | |
try { | |
$response = $this->httpClient->get($uri, ['headers' => ['Accept' => 'text/xml']]); | |
$data = (string) $response->getBody(); | |
} | |
catch (RequestException $e) { | |
$this->logger->error("Error returned from HOLLIS search, error was @error", ['@error' => $e->getMessage()]); | |
} | |
return new Response($data, 200); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment