From e7291fc8867a8e944bda8ed237f9af624ebc9ca9 Mon Sep 17 00:00:00 2001 From: "Abdulmhsen B. A. A" Date: Fri, 26 Apr 2024 15:50:32 +0300 Subject: [PATCH] Added backend search using API --- src/API/Backends/Search.php | 78 +++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 src/API/Backends/Search.php diff --git a/src/API/Backends/Search.php b/src/API/Backends/Search.php new file mode 100644 index 00000000..30d0ae66 --- /dev/null +++ b/src/API/Backends/Search.php @@ -0,0 +1,78 @@ +get('id', null)); + $query = $params->get('query', null); + + if (null === $id && null === $query) { + return api_error('No search id or query string was provided.', HTTP_STATUS::HTTP_BAD_REQUEST); + } + + try { + $backend = $this->getClient(name: $name); + } catch (RuntimeException $e) { + return api_error($e->getMessage(), HTTP_STATUS::HTTP_NOT_FOUND); + } + + if (null !== $id) { + $data = $backend->searchId($id, [Options::RAW_RESPONSE => (bool)$params->get('raw', false)]); + } else { + $data = $backend->search( + query: $query, + limit: (int)$params->get('limit', 25), + opts: [Options::RAW_RESPONSE => (bool)$params->get('raw', false)] + ); + } + + if (count($data) < 1) { + return api_error(r("No results are found for '{query}'.", [ + 'query' => $id ?? $query + ]), HTTP_STATUS::HTTP_NOT_FOUND); + } + + $apiUrl = $request->getUri()->withHost('')->withPort(0)->withScheme(''); + $response = [ + 'results' => $id ? [$data] : $data, + 'links' => [ + 'self' => (string)$apiUrl, + 'backend' => (string)$apiUrl->withPath(parseConfigValue(Index::URL . '/' . $name)), + 'list' => (string)$apiUrl->withPath(parseConfigValue(Index::URL)), + ], + 'options' => [ + 'raw' => (bool)$params->get('raw', false), + ], + ]; + + if (null === $id && $query) { + $response['options']['limit'] = (int)$params->get('limit', 25); + } + + return api_response(HTTP_STATUS::HTTP_OK, $response); + } + +}