tommybananas / finale

Create flexible REST endpoints and controllers from Sequelize models in your Express app
187 stars 36 forks source link

Sort search and group for fields on included models #57

Closed drama-ostrich closed 4 years ago

drama-ostrich commented 4 years ago

This fixes 3 Issues for list.js I've run into while dealing with included/associated models in a resource. I've tried to isolate these 3 problems in tests but the behavior changes based on if the resource has options.subQuery = true/false set and if the associations between models are one-to-many or many-to-many. Ideally I'm looking to be able to sort, search, and group by fields on included models at the same time.

1. Group By breaks pagination

Current Version

If you use a group command (my test example is context.options.group = ['users.id']) then the sequelize findAndCountAll() method returns a list of grouped counts instead of one count number.

Change

If options.group is set then split the find and count into two queries.

2. Sort by field on associated model

Current Version

Sorting by a field on an included model doesn't work. Sequelize uses the wrong table name for the nested field when generating SQL

Change

I use a Sequelize.literal() in the sort if the field path has a period in it.

3. Search with "LIKE" on a associated resource

Current Version

If you want to search for a field on an associated resource you have the following options

  1. Use the name of the field as the url param. My example is ?profile.nickname=name
  2. Specify a search object on the resource definition to choose your own param name. If you choose this method you need to use the Sequelize.Op.eq operator, otherwise the search is picked up as a stringOperator in list.js:115 and throws an error because the path to the included model isn't a sequelize.STRING

Change

I exclude search keys with a period in the serach for stringOperators to allow using Sequelize.Op.like in the search definition in the resource

Note: the field name in the search definition still requires the dollars around the field e.g. $profile.nickname$

drama-ostrich commented 4 years ago

Also if you want me to open individual issues and make PRs to the individual issues let me know

tommybananas commented 4 years ago

This is fantastic. Would you be able to add documentation surrounding anything that is not already documented? I will review this asap and we can get this merged. Thanks much

drama-ostrich commented 4 years ago

@tommybananas Hey yep I'll try to get some docs updates for you soon. I've been taking notes as I've been working with finale.

tommybananas commented 4 years ago

I realize there may not be a lot to say but if you could run your eyes over it and document what you think is important, that would be awesome! Thanks for the contributions