What you'll learn
  • how to create custom sort enums
  • how to resolve custom sort in DynamoDB system
  • how to resolve custom sort in DynamoDB+Elasticsearch system

Overview
anchor

Creating the New Sorter for the GraphQL Schema
anchor

The first thing users need to do is to add a CmsEntryFieldSortingPlugin:

apps/api/headlessCms/src/plugins/customSorterPlugin.ts

And then add the plugin into the plugins array of the createHandler():

apps/api/headlessCms/src/index.ts

Creating the Sort Plugin to Handle New Custom Sorters
anchor

DynamoDB Systems
anchor

As the sorting in the DynamoDB systems is basic, let’s show the example on how to sort via a nested object value:

apps/api/headlessCms/src/plugins/yourCustomSortPlugin.ts

And then add the plugin into the plugins array of the createHandler():

apps/api/headlessCms/src/index.ts

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 interfaceexternal link
  • 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
anchor

apps/api/headlessCms/src/plugins/yourCustomSortPlugin.ts

And then add the plugin into the plugins array of the createHandler():

apps/api/headlessCms/src/index.ts

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
anchor

While custom sorters are a powerful functionality, use them carefully as it might degrade the system performance - especially in the DynamoDB systems.