# Add Pagination to a Koa REST API

Yes. An agent adds page and limit parameters to your Koa list endpoint with TypeORM, documents them in Swagger, updates the Jest mocks, and opens a PR.

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

## What the agent does

The agent reads the endpoint it is changing. In an API laid out like javieraviles/node-typescript-koa-rest, `src/controller/user.ts` is a class of static handlers decorated with `koa-swagger-decorator`, and `getUsers`, mounted at `GET /users` in `src/protectedRoutes.ts` behind the `koa-jwt` middleware, calls `getManager().getRepository(User).find()` and sets the whole array as `ctx.body`. The `User` entity in `src/entity/user.ts` has an `id` from `PrimaryGeneratedColumn`, a `name` of 10 to 80 characters and an `email` of 10 to 100, and TypeORM 0.2.32 runs with `synchronize: true` against Postgres, whose local instance `docker-compose.yml` starts as `postgres:10-alpine`. The Swagger page served at `/swagger-html` is generated from the same decorators, and `README.md` documents `GET /users` as returning the collection.

It then reads what guards the change. `tests/controller/user.test.ts` mocks `typeorm`'s `getManager` and asserts that `getUsers` calls `find` once and sets status 200 with the array; `npm run lint` runs `tsc --noEmit` and ESLint with `--fix`; `npm run build` runs lint, `tsc` and `copyStaticAssets.ts`; `integrationtests/` holds a Postman collection that `newman` runs against a live server, and `package.json` declares Node 14. The delete handler compares `ctx.state.user.email` with the row, which shows the JWT payload shape the list handler can rely on.

The change keeps the route and adds two query parameters. `getUsers` reads `page` and `limit` from `ctx.query`, defaults them to 1 and 20, caps `limit` at 100, answers 400 with a message when either is not a positive integer, and calls `findAndCount` with `skip`, `take` and `order: { id: 'ASC' }`, since a page without a stable order repeats rows between requests. The body becomes `{ data, page, limit, total }`, and a `@query` decorator beside `@request` and `@summary` describes the two parameters so the Swagger page shows them with their defaults and the cap. The agent updates the README table and the Postman collection's assertion on `GET /users` to read `data`, and extends the Jest test with a `findAndCount` mock returning a tuple, plus cases for `limit=0` and `page=abc`.

In its sandbox the agent starts Postgres with the compose file, copies `.example.env` to `.env`, runs `npm ci`, `npm run lint` and `npm test`, then `npm run watch-server`. With the demo bearer token from the README it creates twenty-five users through `POST /users`, requests `/users?page=2&limit=10` and `/users?limit=500`, and pastes the responses and the 400 for `page=0`. It runs the Postman collection with `newman` against the local server, keeping its summary, and deletes the test users through the route the controller provides.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add pagination to the users list endpoint of this Koa API. Read src/server.ts, src/protectedRoutes.ts, src/controller/user.ts, src/entity/user.ts, src/config.ts, tests/controller/user.test.ts, integrationtests/, README.md, docker-compose.yml and package.json first. In getUsers, read page and limit from the query string with defaults of 1 and 20, a cap of 100 and a 400 for values that are not positive integers, query with findAndCount using skip, take and an ascending order on id, and return an object with data, page, limit and total. Describe both parameters with koa-swagger-decorator's query decorator so the Swagger page shows them. Update the README table, the Postman collection's assertion on the list route and the Jest test's typeorm mock, adding cases for the defaults, the cap and a bad value. Start Postgres with the compose file, run lint and the Jest suite, start the server, create enough users to fill three pages with the README's token, request two pages and an over-cap limit, run the Postman collection with newman, and open a pull request that pastes those responses and the test output. Do not change the other routes or the entity.",
  "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

The pull request changes `src/controller/user.ts`, `tests/controller/user.test.ts`, the Postman collection under `integrationtests/` and the README's route table. Its description pastes the three responses from the running server, a second page of ten, a request with `limit=500` answered with `limit: 100`, and the 400 for `page=0`, followed by the Jest summary with the new cases and the `newman` summary against the local server.

A note explains the one visible change for clients: `GET /users` now answers an object rather than a bare array, with the old rows under `data`, and names the alternative of keeping the array and sending the total in a header if a client cannot be updated.

Before merging, a reviewer decides the default and maximum page size, whether an `order` on `id` should become `created_at` once the entity has one, and whether the Swagger version string in `protectedRoutes.ts` should move for the changed response shape.

## Run it on every list endpoint that returns a whole table

In the console, an automation on the Project with a `linear` trigger on `linear.issue.labeled` filtered to a `pagination` label and this prompt starts one run per labelled issue, in its own sandbox, ending in one pull request. The issue's text follows the prompt as data, so an issue that names another list route or asks for a `cursor` parameter instead makes its own change, and changes made by an app integration never fire the trigger, so the agent's own comment on the issue starts nothing.

From your own server the same run is one `POST /o/{org}/sessions` per issue, with the repository in `resources` and the issue's `https://linear.app/<workspace>/issue/<ID>` URL there too, so Rush reads it through your Linear connection into the prompt. A `webhook_url` on the key reports `run.completed` or `run.failed` with the `session_url` when the turn finishes.

## Why run it on Rush?

Pagination is easy to write and easy to get subtly wrong: an unordered `skip` and `take` repeats rows, a missing cap lets a client ask for the whole table, and the response shape change breaks the integration tests nobody runs locally. The agent brings Postgres up with the repository's own compose file, fills three pages, requests them and runs the Postman collection, so the pull request shows the endpoint behaving rather than the diff that should make it behave.

Every choice is from this repository: the decorators the Swagger page is built from, the Jest mock shape the existing test uses, the demo token in the README and the `deleteTestUsers` route for cleanup. The commands and their output stay with the run, and the same prompt can be sent for every list route a team owns.

## Frequently asked questions

### Does the response shape change?

Yes. `GET /users` answers `{ data, page, limit, total }` instead of a bare array, because a client needs `total` to render page controls. The agent updates the README and the Postman collection with it, and the description names the header-based alternative for a client that cannot change.

### Why order by id?

Postgres returns rows in no guaranteed order without an `ORDER BY`, so two requests for page 2 can overlap or skip rows. The entity has no timestamp column, so `id` ascending is the only stable key, and the description says to switch to a creation time if one is added.

### What happens with limit=500 or page=0?

`limit` above 100 is clamped to 100 and the response says so in its `limit` field; `page` or `limit` that is not a positive integer is a 400 with a one-line message, consistent with the 400s the controller already uses for a missing user. Both cases are in the Jest test and were requested against the running server.

### Will the Swagger page show the parameters?

Yes. The handler gains a `query` decorator from `koa-swagger-decorator` beside the existing `request` and `summary` decorators, so the page at `/swagger-html` lists `page` and `limit` with their types, defaults and the cap.

## More Koa jobs

- [Add Prometheus Metrics to a Koa API](https://getrush.ai/run/add-prometheus-metrics/koa/)
- [Add Rate Limiting to a Koa App](https://getrush.ai/run/add-rate-limiting/koa/)
- [Add Request ID Logging to a Koa App](https://getrush.ai/run/add-request-id-logging/koa/)

## The same job on other stacks

- [Add Pagination to a Prisma Query](https://getrush.ai/run/add-pagination/prisma/)
- [Add Pagination to a Quarkus REST API](https://getrush.ai/run/add-pagination/quarkus/)
- [Add Pagination to a Sequelize Express API](https://getrush.ai/run/add-pagination/sequelize/)

## 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/)
