# Add Cursor Pagination to a TypeORM + NestJS API

Yes. An agent turns the limit and offset paging in your TypeORM query builders into a keyset cursor on (created, id), keeps the old shape working, and opens a PR.

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

## What the agent does

The agent reads the list queries before it changes them, because a cursor has to match the ordering the code already uses. In an API laid out like lujakob/nestjs-realworld-example-app, `findAll` and `findFeed` in `src/article/article.service.ts` build a `createQueryBuilder('article')` from `getRepository(ArticleEntity)`, order by `article.created` descending, call `getCount()` for `articlesCount`, then apply `qb.limit(query.limit)` and `qb.offset(query.offset)` when those keys are in the query string and finish with `getMany()`. `findAll` also does `leftJoinAndSelect('article.author', 'author')` and filters by `tag`, `author` and `favorited`; `findFeed` first reads `FollowsEntity` rows for the user and filters `article.authorId IN (:ids)`. `ArticleEntity` in `article.entity.ts` has a generated integer `id`, a `created` column of type `timestamp` defaulting to `CURRENT_TIMESTAMP`, and an eager `comments` relation. `package.json` pins `typeorm` ^0.2.24, `@nestjs/typeorm` ^7, `mysql` ^2.18 and `jest` ^25 with `ts-jest`, `ormconfig.json.example` is a MySQL config with `synchronize: true`, and the only test is `src/tag/tag.controller.spec.ts`.

Two facts shape the design. First, MySQL's `timestamp` column holds whole seconds, so two articles created in the same second tie on `created`, and a keyset on `created` alone would skip or repeat one of them at a page boundary; the cursor is therefore the pair `(created, id)`, ordered `created DESC, id DESC`. Second, TypeORM's own documentation says `limit` and `offset` on a query builder with joins can return fewer root rows than asked, and `findAll` joins `author` and eager-loads `comments`; the agent switches both methods to `take`, which TypeORM applies to the root entity, and says in the pull request why the one-word change matters here.

The change is one helper and two call sites. `src/article/cursor.ts` encodes `{created, id}` as a base64url string and decodes it back, throwing a `BadRequestException` on anything else so a tampered `after` answers 400. In `findAll` and `findFeed`, an `after` query parameter adds `andWhere('(article.created < :created OR (article.created = :created AND article.id < :id))', …)`, the order becomes `created DESC, id DESC`, and `take` asks for `limit + 1` rows; the extra row, when present, becomes the `nextCursor` field beside `articles` and `articlesCount` in `ArticlesRO` in `article.interface.ts`. `limit` is parsed with a default of 20 and a cap of 100 rather than passed through as a string, and `offset` keeps working for one release when no `after` is sent, so the RealWorld frontends that paginate with `offset` today keep working. `articlesCount` is still computed on the first page and skipped on cursor pages, which is most of the saving. The `favorited` filter reads `author.favorites` from a `findOne` that loads no relations, which the agent notes in the pull request as a pre-existing fault it leaves alone.

For tests, the agent adds `src/article/cursor.spec.ts` for the encoder and the 400 on garbage input, which runs under the existing `jest.json` with no database, and `src/article/article.service.spec.ts` built with `Test.createTestingModule` the way `tag.controller.spec.ts` is, with `TypeOrmModule.forRoot()` reading `ormconfig.json`. That needs MySQL, so in its sandbox it installs MariaDB with `apt-get`, creates the `nestjsrealworld` database the README names, copies `ormconfig.json.example` and `src/config.ts.example` into place, runs `npm install`, then `npm test`. It starts the app with `npm start`, registers a user, creates three articles in quick succession so at least two share a `created` second, and walks `GET /api/articles?limit=2` by following `nextCursor` until it is absent, checking that all three slugs appear once.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add cursor pagination to the article list and feed in this NestJS + TypeORM API. Read package.json, jest.json, ormconfig.json.example, src/main.ts, src/app.module.ts, src/article/article.service.ts, src/article/article.controller.ts, src/article/article.entity.ts, src/article/article.interface.ts, src/user/user.entity.ts, src/profile/follows.entity.ts and src/tag/tag.controller.spec.ts first. The created column is a MySQL timestamp with whole seconds, so use a keyset on (created, id) ordered created DESC, id DESC. Write src/article/cursor.ts that encodes and decodes a base64url cursor of created and id and throws BadRequestException on anything else. In findAll and findFeed, when an after query parameter is present add the keyset where clause, use take instead of limit and offset because findAll joins author and eager-loads comments, ask for limit plus one rows, and return the extra row as nextCursor beside articles and articlesCount. Parse limit with a default of 20 and a cap of 100. Keep offset working for one release when no after is sent, and compute articlesCount only on the first page. Note the favorited filter's unloaded favorites relation in the pull request without changing it. Add src/article/cursor.spec.ts and src/article/article.service.spec.ts on the pattern of the tag spec. Install MariaDB in your sandbox, create the nestjsrealworld database, copy the example config files, run npm install and npm test, start the app, create three articles quickly, walk /api/articles?limit=2 by following nextCursor, and paste the walk and the test output into the pull request. Change nothing in create, update, delete, comments or favorites.",
  "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 adds `src/article/cursor.ts`, `src/article/cursor.spec.ts` and `src/article/article.service.spec.ts`, and changes `src/article/article.service.ts` and `src/article/article.interface.ts`. Its description pastes the `npm test` summary and the three `curl` responses of the walk, with the `nextCursor` from each page fed into the next and the last page without one, and the SQL TypeORM ran for the cursor page, which the agent captures by setting `logging: ["query"]` in its local `ormconfig.json`, so the reviewer sees the `created < ? OR (created = ? AND id < ?)` condition and the `LIMIT 3`.

A client that sends nothing new gets what it got before plus `nextCursor`: the first page of `/api/articles` is the same 20 rows (or the `limit` it asked for, now capped at 100) in the same order, and `offset` still pages. The description lists the cap and the switch from `limit` to `take` as the two things a reviewer might notice, and explains that `take` is what makes a joined page the right length.

Before merging, a reviewer decides when `offset` goes, whether `articlesCount` on the first page is worth its `COUNT`, and whether the RealWorld frontends they deploy should move to `nextCursor` now; the pull request names the field and leaves the client change to them.

## Run it on every list endpoint paged by offset

An engineer who saw the slow `OFFSET 5000` in a query log starts this from the terminal with this body and moves on. One `POST /o/{org}/sessions` per service, each with its own `resources` URL; the run reads that service's entities and query builders, so the cursor columns and the join handling come from the code rather than from a generic snippet.

Send a `request_id`, a UUID, with each body so a retried call returns the run it already started. A key runs at most `max_concurrent` sessions at once, 4 by default, and a request past that answers `202` with `status: "queued"` and starts when a slot frees. With a `webhook_url` on the key, Rush posts `run.completed` for each run the key started, and `data.session_url` reads back the pull request link.

## Why run it on Rush?

Keyset pagination on TypeORM has two traps that compile fine and fail in production: a cursor on a one-second `timestamp` that drops rows at a boundary, and `limit` on a joined query builder that returns short pages. The agent reproduces both against a real MariaDB in its own sandbox, creating articles fast enough to tie on `created` and walking the pages, and the pull request carries that walk rather than a promise.

The transcript keeps every command and its output, so the reviewer reads the SQL that ran, each page's body and the test summary without checking the branch out. Several services can be converted at once, each run in its own sandbox with its own database, and nothing merges until a person reads the diff.

## Frequently asked questions

### Why is the cursor on created and id rather than id alone?

The list is ordered by `created` descending, and an `id` cursor would change that order. `created` is a MySQL `timestamp` with one-second precision, so it is not unique; the `(created, id)` pair is, and the where clause compares the pair so a boundary between two articles created in the same second is handled. The test creates three articles quickly to cover exactly that case.

### Why switch from limit and offset to take?

`findAll` joins `author` and `comments` are eager, so the SQL has more rows than articles. TypeORM's documentation warns that `limit` applies to those joined rows and may return fewer articles than asked; `take` applies to the root entity. The change is one word per call site, and the pull request quotes the warning.

### Does it still return articlesCount?

On the first page, yes, the same `COUNT` as before, because clients use it to show a total. On a cursor page the count is skipped, which is where the saving is: the client already has the total from the first page. The field is absent rather than zero on those pages.

### What about the feed?

`findFeed` gets the same treatment with the same helper. It first reads the followed author ids and filters `authorId IN (:ids)`, and the keyset condition is added beside that filter, so following someone new mid-walk changes later pages and never the cursor arithmetic.

### Will the tests run in CI?

`cursor.spec.ts` needs no database. `article.service.spec.ts` follows the existing tag spec, which calls `TypeOrmModule.forRoot()` and so needs a reachable MySQL and an `ormconfig.json`; this repository has no CI workflow, so the pull request says what a job would need, and the agent ran the suite against MariaDB in its sandbox.

## More TypeORM jobs

- [Add Database Indexes to TypeORM Entities](https://getrush.ai/run/add-database-indexes/typeorm/)
- [Replace TypeORM synchronize with Migrations](https://getrush.ai/run/add-database-migrations/typeorm/)
- [Add a Migration Check to CI for a TypeORM Project](https://getrush.ai/run/add-migration-check-to-ci/typeorm/)

## The same job on other stacks

- [Add Cursor Pagination to an Actix Web API](https://getrush.ai/run/add-cursor-pagination/actix/)
- [Add Cursor Pagination to an aiohttp App](https://getrush.ai/run/add-cursor-pagination/aiohttp/)
- [Add Cursor Pagination to an Axum API](https://getrush.ai/run/add-cursor-pagination/axum/)

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