3

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 ) 
  }
}));
Martin Thompson
  • 3,415
  • 10
  • 38
  • 62

2 Answers2

3

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;
  }
});
Daff
  • 43,734
  • 9
  • 106
  • 120
  • Perfect , thanks. One thing I had to do was set the service to a variable and then execute hooks off that otherwise I got the "app.use requires a middleware function" . Probably goes without saying but I am quite new to nodejs. Cheers. – Martin Thompson Mar 01 '18 at 19:51
  • Oh sorry, `app.use` was supposed to be `app.service`. I updated the answer. – Daff Mar 02 '18 at 07:49
0

Having default sorting works well for me. E.g. you have a field sort_order in some models.

server/app.hooks.js

module.exports = {
  before: {
    find: [() => {
      const { query = {} } = context.params;

      if (context.service.options.Model.attributes.sort_order && !query.$sort) {
         Object.assign(query, { $sort: { sort_order: 1 } });
      }

      return context;
    }],
   }
 };
Denis Rybalka
  • 1,821
  • 3
  • 18
  • 28