From f99768239d8e18d0d24b9098e0a868606b6a155f Mon Sep 17 00:00:00 2001 From: fmizzell Date: Tue, 11 Jun 2019 08:38:39 -0500 Subject: [PATCH] Allowing cross origin requests in our sql api endpoint. (#140) --- .../dkan_datastore/src/Controller/Api.php | 42 +++++++++++++++++-- 1 file changed, 38 insertions(+), 4 deletions(-) diff --git a/modules/custom/dkan_datastore/src/Controller/Api.php b/modules/custom/dkan_datastore/src/Controller/Api.php index d391f49aa4..2704017d44 100644 --- a/modules/custom/dkan_datastore/src/Controller/Api.php +++ b/modules/custom/dkan_datastore/src/Controller/Api.php @@ -22,11 +22,19 @@ class Api implements ContainerInjectionInterface { */ protected $container; + /** + * Factory to generate various dkan classes. + * + * @var \Drupal\dkan_common\Service\Factory + */ + protected $dkanFactory; + /** * Constructor. */ public function __construct(ContainerInterface $container) { $this->container = $container; + $this->dkanFactory = $container->get('dkan.factory'); } /** @@ -40,12 +48,33 @@ public function runQuery($query_string) { $state_machine = $parser->getValidatingMachine(); $query_object = $this->getQueryObject($state_machine); $database = $this->getDatabase(); - $result = $database->query($query_object); - return new JsonResponse($result); + try { + $result = $database->query($query_object); + } + catch(\Exception $e) { + return $this->dkanFactory + ->newJsonResponse( + "Querying a datastore that does not exist.", + 500, + ["Access-Control-Allow-Origin" => "*"] + ); + } + + return $this->dkanFactory + ->newJsonResponse( + $result, + 200, + ["Access-Control-Allow-Origin" => "*"] + ); } else { - return new JsonResponse("Invalid query string."); + return $this->dkanFactory + ->newJsonResponse( + "Invalid query string.", + 500, + ["Access-Control-Allow-Origin" => "*"] + ); } } @@ -59,7 +88,12 @@ protected function getQueryObject($state_machine) { $manager = $this->getDatastoreManager($uuid); } catch (\Exception $e) { - return new JsonResponse("No datastore."); + return $this->dkanFactory + ->newJsonResponse( + "No datastore.", + 500, + ["Access-Control-Allow-Origin" => "*"] + ); } $object = new Query();