Adding Custom field in search results for Decoupled Drupal Architecture

Adding Custom field in search results for Decoupled Drupal Architecture

Nowadays, most of the sites we are working on are built on decoupled Drupal approach. A decoupled website opens up multiple opportunities. Along with new opportunities, we also get our fair share of challenges. One was where I was tasked to create the module, which can take input (string & filetype) from the front end framework and result the dataset along with metadata e.g. image, date, content type and  File Type.

Before we move on with how we implemented this, we need to understand how search function operates in Drupal site. It has three main parts - Source, Index and Results.

Source refers to any kind of content we have on the website. We parse the content and store the metadata in the index. And we display the result in the front-end.

In our case, the front end was built using AngularJS.

First, we had to Identify the schema in which all of our source data was stored. 

The required search page had a basic set of features like title, description, taxonomy, link and some extra metadata like image, date, type and file type. Since we search across multiple sites, we also needed information about the source from where the item comes from.

I created a custom module to create API which can be used for content search like a REST resource using _controller POST method. 

Below is a basic module to explain how we can create Search API to be consumed by the external applications.

We would need to create files as per the below structure.



├── customapi_search.routing.yml

└── src

    └── Controller

        └── SearchAPIController.php

Step 1.  Create file to define the metadata of the module.

Step 2. Create search routing file customapi_search.routing.yml

Additionally, create a customapi_search.routing.yml file in which we can define our path (endpoint), controller and methods.

Step 3. Create a SearchAPIController.php Controller file in which we can define custom _controller with [POST] resources.

In our case, we have used the controller method as rest API using POST method, which extends ControllerBase class and EntityQuery used for fetch data precept to the POST method param value.

Endpoint of Custom search api: /api/content-search

Json query parameters like:

{"q": "test", "firstResult": 0, "numberOfResults": 1000, "filters": {"type": ["page","pdf",”docx”]}, "sortBy": "latest"}

The above module will provide endpoint

Endpoint response output: