API pagination best practices

前端 未结 11 1214
执念已碎
执念已碎 2020-11-28 17:12

I\'d love some some help handling a strange edge case with a paginated API I\'m building.

Like many APIs, this one paginates large results. If you query /foos, you\'

11条回答
  •  [愿得一人]
    2020-11-28 17:56

    I've thought long and hard about this and finally ended up with the solution I'll describe below. It's a pretty big step up in complexity but if you do make this step, you'll end up with what you are really after, which is deterministic results for future requests.

    Your example of an item being deleted is only the tip of the iceberg. What if you are filtering by color=blue but someone changes item colors in between requests? Fetching all items in a paged manner reliably is impossible... unless... we implement revision history.

    I've implemented it and it's actually less difficult than I expected. Here's what I did:

    • I created a single table changelogs with an auto-increment ID column
    • My entities have an id field, but this is not the primary key
    • The entities have a changeId field which is both the primary key as well as a foreign key to changelogs.
    • Whenever a user creates, updates or deletes a record, the system inserts a new record in changelogs, grabs the id and assigns it to a new version of the entity, which it then inserts in the DB
    • My queries select the maximum changeId (grouped by id) and self-join that to get the most recent versions of all records.
    • Filters are applied to the most recent records
    • A state field keeps track of whether an item is deleted
    • The max changeId is returned to the client and added as a query parameter in subsequent requests
    • Because only new changes are created, every single changeId represents a unique snapshot of the underlying data at the moment the change was created.
    • This means that you can cache the results of requests that have the parameter changeId in them forever. The results will never expire because they will never change.
    • This also opens up exciting feature such as rollback / revert, synching client cache etc. Any features that benefit from change history.

提交回复
热议问题