Adding Search to MyJaduAPI

joe's picture

Suraj has described the utility of Directories, and in conjunction with MyJadu API then they have the potential to be used as datastores that are user friendly for websters (easy to update, easy to surface in different applications) and users (information can be accessed in a variety of ways, either the standard UI or applications optimised for singlepageness for example).

One thing I have noticed is that the API does not implement search out-of-the-box; why this is I'm not sure and there may be good reason for this. Anyway, here is a hook into the pre-existing directories search:

1. In /jadu/API/Resources/Directories.php add the following function:

    /**
     * Retrieve a list of all of matched directory entries
     *
     * @return DOMDocument
     */
    public function search()
    {
        $directoryId = $this->getArgument('id', 'GET', -1);
        if ($directoryId < 1) {
            return 1013;
        }
       
        $directory = getDirectory($directoryId);
        if ($directory->id == -1) {
            return 1014;
        }

        $term = $this->getArgument('term', 'GET', false);
        if (!$term) {
            return 1009;
        }

         $entries = searchDirectoryEntryValues($directoryId, $categoryID = -1, $term, $onlyLive = false, $offset = -1, $numRows = -1);
       
        $rootNode = $this->_dom->createElement('entries');
        $rootNode->setAttribute('directory_id', (string)$directoryId);
        $this->_dom->appendChild($rootNode);
       
        $this->_processDirectoryEntries($rootNode, $entries);
       
        return $this->_dom;
    }

2. At the end of Directories.php register the new function:

    /**
    * Returns the names of public methods for this class.
    * @return array[]string
    */
    public function getPublicMethods()
    {
        return array (
            'all',
            'category',
            'fields',
            'entries',
            'search'
        );
    }


3. Searching via the API may need additional URL rules, but it's possible to access the API directly:

/api.php?api_key=<insert api key here>'&resource=directories&id=<insert directory id>&method=search&term=<insert search term>

Cheers
Joe