Search code examples
sequelize.jsfeathersjs

How Can I set the default Sort order in FeathersJs


I have an issue with Feathersjs , integrating with sequalize. If I set the default pagination like below, and there is no sort specified it will generate an error because the SQL statement generated is invalid.

Service Created with default of 5:

app.use('/manifests', service({
  paginate: {
    default: 5,
    max: 25
  }
}));

SQL Statement Generated ( setting a limit of 20 )

SELECT [id], ...etc
FROM [Manifest] AS [Manifest] OFFSET 0 ROWS FETCH NEXT 20 ROWS ONLY

It Makes sense to set a default order , but I am not sure how to do that in the service.

The SQL Statement I want to achieve in this case is

SELECT [id], ...etc
FROM [Manifest] AS [Manifest] ORDER BY Date desc OFFSET 0 ROWS FETCH NEXT 20 ROWS ONLY

I would like to somehow set the default for this..?

app.use('/manifests', service({
  paginate: {
    default: 5,
    max: 25
  }
  sort:{
    default: date -1  ( or something ) 
  }
}));

Solution

  • Feathers hooks allow you to modify the query to what you need by adding the $sort common query parameter if it is not set:

    app.service('/manifests').hooks({
      before(context) {
        const { query = {} } = context.params;
    
        if(!query.$sort) {
          query.$sort = {
            date: -1
          }
        }
    
        context.params.query = query;
      }
    });