# Add Pagination to a Sequelize Express API

Yes. An agent adds page and limit query params to your Sequelize list routes with findAndCountAll, returns totals, tests it with node:test, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-pagination/sequelize/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads the routes before it changes their shape. In a Sequelize app like the `express-main-example` in sequelize/express-example, `package.json` has `express` `^4.17.1`, `sequelize` `^6.3.3`, `sqlite3` `^5.0.0` and `body-parser` `^1.19.0`, scripts `start` and `setup-example-db`, `engines` of `node >=10`, no test script and no dev dependencies, and `.npmrc` sets `package-lock=false`. `express/app.js` maps `users`, `instruments` and `orchestras` to controllers and wires `getAll` to `GET /api/:route`, `getById`, `create`, `update` and `remove` through `makeHandlerAwareOfAsyncErrors`. Every `getAll` calls `findAll()` with no `limit`: `express/routes/users.js` returns every user, and `express/routes/orchestras.js` returns every orchestra with `include: models.instrument` when `includeInstruments` is in the query. `express/helpers.js` has `getIdParam`, which throws a `TypeError` on a non-numeric id. `sequelize/index.js` opens SQLite at `sqlite-example-database/example-db.sqlite` with `logQueryParameters` and `benchmark`, defines the three models and `applyExtraSetup` adds `orchestra.hasMany(instrument)`; `sqlite-example-database/setup.js` seeds four users, three orchestras and ten random instruments each with `sync({ force: true })`.

The agent adds `getPagination(req)` to `express/helpers.js`: `page` defaults to 1, `limit` to 20 and is capped at 100, both must match `^\d+$` like `getIdParam` or a `TypeError` is thrown, and it returns `{ page, limit, offset: (page - 1) * limit }`. Each `getAll` switches to `findAndCountAll({ limit, offset, order: [['id', 'ASC']] })`, because without an `order` SQLite may return pages in different sequences; the orchestras controller adds `distinct: true` when it includes instruments so `count` is the number of orchestras and not of joined rows. The response becomes `{ data: rows, page, limit, total: count, totalPages }` with an `X-Total-Count` header, which is a change of shape from the bare array, stated plainly in the description. In `express/app.js` the agent adds a four-argument error middleware that turns a `TypeError` thrown by a helper into a 400 with the message, which also fixes the current 500 on `GET /api/users/abc`; the root page's hint text mentions `?page=` and `?limit=`.

There is no test runner, so the agent adds one that needs nothing beyond Node: `node --test` with `supertest` as the only dev dependency and a `test` script. `sequelize/index.js` reads `process.env.DB_STORAGE` with the current path as the default, so tests set `DB_STORAGE=:memory:`, call `sequelize.sync({ force: true })` and seed 25 instruments with `bulkCreate` in `before`. `test/pagination.test.js` asserts that `GET /api/instruments?page=2&limit=10` returns ten rows, `total` 25 and `totalPages` 3, that `?limit=1000` is capped to 100, that `?page=abc` answers 400, that `/api/orchestras?includeInstruments&limit=2` reports `total` equal to the number of orchestras, and that `GET /api/users` with no parameters uses the defaults.

`node:test` needs a newer Node than the `>=10` in `engines`, so the agent raises `engines.node` and says so in the description rather than hiding it. It runs `npm install`, `npm run setup-example-db`, `npm test` and `npm start` once with a `curl` of `/api/orchestras?includeInstruments&page=1&limit=2` to show the `distinct` count, and keeps the output. `readme.md` lists the new parameters and the response shape under the route list. The models, `extra-setup.js` and the seed script are unchanged.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add pagination to this Sequelize and Express API. Read package.json, .npmrc, express/app.js, every file in express/routes, express/helpers.js, sequelize/index.js, the models and the setup script first. Add a helper that parses page and limit with defaults, a cap and strict integer validation in the style of the existing id helper, switch every list route to findAndCountAll with a stable order and offset, use distinct when a route includes an association, and return rows with page, limit, total and totalPages plus an X-Total-Count header. Map helper TypeErrors to 400 with an error middleware. Make the database path overridable through an environment variable, add node:test tests with supertest against an in-memory SQLite covering a middle page, the cap, a bad page value, the distinct count with an include and the defaults, and add a test script. If node:test needs a newer Node than engines allows, raise engines and say so. Run the setup script, the tests and one curl against the running server and include the output. Document the parameters in the readme. Open a pull request.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request that changes `express/helpers.js`, `express/routes/users.js`, `express/routes/instruments.js`, `express/routes/orchestras.js`, `express/app.js`, `sequelize/index.js`, `package.json` (`supertest`, the `test` script, `engines`) and `readme.md`, and adds `test/pagination.test.js`. The models, associations and seed script are unchanged.

The description states the response shape change and the `engines` bump as the two things a reviewer must accept, lists each test, quotes the `node --test` summary and the `curl` output showing `total` and `totalPages` for the included query. The commands and full output are in the transcript at `GET /o/{org}/sessions/{id}/messages`.

Before merging, a reviewer decides whether existing clients can take the new envelope or whether the array should stay when no `page` or `limit` is sent, and whether 20 and 100 are the right default and cap. A follow-up message to the same session can switch to cursor pagination on `id` for the instruments route, or keep the bare array behind a header.

## Run it on every List endpoint that returns the whole table

A team with several Express services starts one run per repository with one `POST /o/{org}/sessions` each, the repository in `resources` and this prompt as `input`. Each run reads its own controllers, so a service whose lists already take `offset` gets `page` mapped onto it, and one on Postgres gets the same `findAndCountAll` with its own dialect.

Send a `request_id`, a UUID v5 of the repository's full name, so a retried call returns the run it already started. The key's `webhook_url` reports when each run the key starts finishes, with the run's final answer in `result`.

## Why run it on Rush?

Pagination is one query option and three mistakes: no `order` so pages overlap, `count` inflated by a join, and a parser that lets `?limit=-1` through. The agent reads every list route and association, adds `distinct` where an include exists, and proves each case with a seeded in-memory database under `node:test` in a sandbox of its own, with the output kept.

The pull request names the two decisions it cannot make for you, the response shape and the Node floor, beside the passing tests, so review is a diff and two answers rather than a local database and a spreadsheet of expected counts. Several services can be done at once, each in its own sandbox with its own pull request.

## Frequently asked questions

### Does the response shape have to change?

Not necessarily. The default here is an envelope with `data`, `page`, `limit`, `total` and `totalPages`, because clients need the total. Say in the prompt if you want the bare array kept when no parameters are sent, or the totals only in headers, and the agent does that instead.

### Why findAndCountAll and not two queries?

It runs the count and the page in one call with the same `where` and `include`, and with `distinct: true` the count stays correct when an association is included. For very large tables the count can be slow; a follow-up can switch to cursor pagination that needs no count.

### Will this touch the SQLite file or the seed script?

No. Tests run against `:memory:` through the new `DB_STORAGE` variable, and the seed script still writes `sqlite-example-database/example-db.sqlite` as before.

### Why raise the Node engines field?

`node --test` and `node:test` are not in Node 10, and the repository has no other test runner. The agent raises the floor to a version that ships them and says so; if you would rather stay on the old floor, say which runner to add instead.

## More Sequelize jobs

- [Add Prometheus Metrics to an Express and Sequelize API](https://getrush.ai/run/add-prometheus-metrics/sequelize/)
- [Add Slow Query Logging to a Sequelize App](https://getrush.ai/run/add-slow-query-logging/sequelize/)
- [Add Soft Delete to Sequelize Models in an Express App](https://getrush.ai/run/add-soft-delete/sequelize/)

## The same job on other stacks

- [Add Pagination to a Slim 4 List Endpoint](https://getrush.ai/run/add-pagination/slim/)
- [Add Message History Pagination to a Socket.IO Chat](https://getrush.ai/run/add-pagination/socket-io/)
- [Add Pagination to a Wagtail Blog Index](https://getrush.ai/run/add-pagination/wagtail/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
