Headless CMS > extensions
Custom Sorting
Learn how to create custom sorting for user defined models
- how to create custom sort enums
- how to resolve custom sort in DynamoDB system
- how to resolve custom sort in DynamoDB+Elasticsearch system
Overview
Creating the New Sorter for the GraphQL Schema
The first thing users need to do is to add a CmsEntryFieldSortingPlugin
:
And then add the plugin into the plugins array of the createHandler()
:
Creating the Sort Plugin to Handle New Custom Sorters
DynamoDB Systems
As the sorting in the DynamoDB systems is basic, let’s show the example on how to sort via a nested object value:
And then add the plugin into the plugins array of the createHandler()
:
This plugin matches the myCustomSorting
value from myCustomSorting_ASC
and then it creates sort variables which are used in our built-in sorting, which uses lodash.orderBy
library.
Variables are:
- field - check out the interface
- fieldId - full path to the field in the
fields
object - it is used for error reporting if it happens - valuePath - full path to the field in the database record - it is used to get the value by which we are going to sort
- reverse - in which order will the records go to the API response
Although we gave an example to sort by nested objects, please do not do that in production as it will get quite slow at some point.
Elasticsearch Systems
And then add the plugin into the plugins array of the createHandler()
:
With this plugin, we replace the sort completely as it would fail. There is no myCustomSorting
field and the Elasticsearch query would fail when it would hit the server.
Note that we used the CmsEntryElasticsearchBodyModifierPlugin
in the example because we needed to replace whole sort
object on the body
. If you need to modify the sort (add or remove something), feel free to use the CmsEntryElasticsearchSortModifierPlugin
.
Conclusion
While custom sorters are a powerful functionality, use them carefully as it might degrade the system performance - especially in the DynamoDB systems.