tommybananas / finale

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

Filtering/sorting by association fields #20

Closed gibonu closed 6 years ago

gibonu commented 6 years ago

hi is there any way to filter/sort by association fields?

I have a Project model with FK to User as project manager. I have turned on associations in sequelize and finale but now I want to be able to select all projects with project manager last name being XXXX.

It is achievable via sequelize so I assume it should be somehow possible with epilogue as well? My resources are defined like that:


var resources = Object.keys(app.get('models'));
resources.pop();

resources.forEach(function (resource) {
   var res = finale.resource({
   model: app.get('models')[resource],
   endpoints: ['/' + resource, '/' + resource + '/:id'],
   associations: true,
 });
});

where models are sequelize models

tommybananas commented 6 years ago

There are a couple ways to accomplish this but I would hit the project manager endpoint with the last name search and then include projects via associations.

GET /project-managers?lastName=smith
var PM = finale.resource({
    model: models.projectmanager,
    endpoints: ['/pms', '/pms/:id'],
    include: [ models.project ]
});
gibonu commented 6 years ago

Thanks for the answer.

This was my attempt as well at first but I display data in grid. I have CRUD app, pretty simple but I need to enable filtering/sorting by different properties of the object. It works well as long as I filter either by project properties or manager properties (so my app can switch which endpoint to hit based on that) but it fails when i do try filtering by both. Looking at source and going through docs it made me realize I can use fetch.before milestone to define included models and how to filter. But as this has to be prepared 'beforehand' and my grid is configurable so I don't know which fields even will be used for filtering (I have to assume all) it produces not the nicest SQL code adding all manager fields inside inner join. Ideally would be to make it work like in finale/epilogue core where it checks if given field is added in request and add it to where clause or not.

INNER JOIN [Manager] AS [Manager] ON [Project].[ManagerID] = [Manager].[ID]
AND ([Manager].[ID] LIKE N'%%'
     AND [Manager].[Login] LIKE N'%reqlogin%'
     AND [Manager].[FirstName] LIKE N'%%'
     AND [Manager].[LastName] LIKE N'%%'
     AND [Manager].[Email] LIKE N'%%')

For now this kind of does job for me as this is just POC but if there are other ways to accomplish it I'd be grateful for sharing.

tommybananas commented 6 years ago

I would maybe use milestones to check for query params and load the filtered objects yourself. Not sure if there is a good way to filter both right now but if anyone has any ideas, feel free to reopen.