dchester / epilogue

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

Content-Range when there is association, counts the inner object as well. #198

Open zivchen opened 7 years ago

zivchen commented 7 years ago

Hi I have 2 object, Test and Step. Test has many Steps. I have 4 Tests and 200 steps. model definition: endpoints.testResource = epilogue.resource({ model: models.Test, endpoints: ['/admin/api/tests', '/admin/api/tests/:id'], associations: true });

when doing get-> /tests i get content range 0-4/ 204. so my admin shows pagination when there are none. if i remove the association its great. thanks.

Ziv

xtr0 commented 7 years ago

@zivchen As a workaround you can try the following:

endpoints.testResource.list.fetch.before = function (req, res, context) {
    context.options = context.options || {};
    context.options.distinct = true;

    return context.continue;
}

At least it works for me

zlatinejc commented 7 years ago

Distinct could be set as default and mentioned in the docs.

kvanbere commented 7 years ago

This workaround isn't working for me, here's what I did:

    let accounts = epilogue.resource({
        model: models.Account,
        endpoints: ['/accounts', '/accounts/:id'],
        associations: true
    });
    accounts.list.fetch.before = function (req, res, context) {
        context.options = context.options || {};
        context.options.distinct = true;

        return context.continue;
    };

Request is i.e. accounts?offset=70&count=10

I'm getting a response Content-Range:items 70-79/153 but there are only 111 rows.

edrpls commented 7 years ago

@kvanberendonck it didn't work for me either, I think it's also a bug in sequelize, at least with mysql, I ended up doing two queries and merging the associations.

kvanbere commented 7 years ago

I made it work ! I'll share solution when I get off lunch

kvanbere commented 7 years ago

@edrpls

    let fixPagination = (endpoint) => {
        endpoint.use({ list: { fetch: { before: function(req, res, context) {
            context.options = context.options || {};
            context.options.distinct = true;
            return context.continue;
        }}}});
    };

//...

    let foo = epilogue.resource({
        model: models.Foo,
        endpoints: ['/foo', '/foo/:id'],
        associations: true
    });
    fixPagination(foo);

Using foo.list.fetch.before for example wasn't actually working as a hook. Need to use .use() for some reason.