diff --git a/includes/RestApi/AISearchController.php b/includes/RestApi/AISearchController.php index 9cc9c07..72c375d 100644 --- a/includes/RestApi/AISearchController.php +++ b/includes/RestApi/AISearchController.php @@ -52,6 +52,18 @@ public function register_routes() { ), ) ); + + register_rest_route( + $this->namespace, + '/' . $this->rest_base . '/default', + array( + array( + 'methods' => \WP_REST_Server::CREATABLE, + 'callback' => array($this, 'get_default_search_results'), + 'permission_callback' => array($this, 'check_permission'), + ), + ) + ); } /** @@ -85,6 +97,23 @@ public function get_search_result( \WP_REST_Request $request ) { return new \WP_REST_Response( $response, 200 ); } + /** + * Proxy to AI service for getting default search results + * + * @param \WP_REST_Request $request Request object + * + * @returns \WP_REST_Response|\WP_Error + */ + public function get_default_search_results( \WP_REST_Request $request ) { + $response = AISearchUtil::get_default_search_results(); + + if ( array_key_exists( 'error', $response ) ) { + return new \WP_Error( 'ServerError', $response['error'] ); + } + + return new \WP_REST_Response( $response, 200 ); + } + /** * Check permissions for routes. * diff --git a/includes/Utils/AISearchUtil.php b/includes/Utils/AISearchUtil.php index fc744aa..a074e8c 100644 --- a/includes/Utils/AISearchUtil.php +++ b/includes/Utils/AISearchUtil.php @@ -22,6 +22,17 @@ private static function _check_capabilities( ) { return $help_enabled && $ai_enabled; } + /** + * The function to check just Help capability + */ + private static function _check_help_capability() { + $capability = new SiteCapabilities(); + + $help_enabled = $capability->get('canAccessHelpCenter'); + + return $help_enabled; + } + /** * The function to proxy to the AI service and get a response * @@ -78,4 +89,45 @@ public static function get_search_results( ); } } + + /** + * The function to get the default results from the proxy + * + * @return array + */ + public static function get_default_search_results() { + if (!self::_check_help_capability()) { + return array( + 'error' => __('We are unable to process the request at this moment'), + ); + } + + $response = wp_remote_post( + NFD_AI_SERVICE_BASE, + array( + 'method' => 'POST', + 'headers' => array( + 'Content-Type' => 'application/json', + ), + 'timeout' => 60, + ) + ); + if ( wp_remote_retrieve_response_code( $response ) !== 200 ) { + return array( + 'error' => __('We are unable to process the request at this moment'), + ); + } + + $parsed_response = json_decode( wp_remote_retrieve_body( $response ), true ); + + try { + return array( + 'posts' => $parsed_response['payload']['posts'], + ); + } catch ( \Exception $exception ) { + return array( + 'error' => __( 'We are unable to process the request at this moment' ), + ); + } + } }