# Add Soft Delete to a Koa API

Yes. An agent adds a deleted-at column to your TypeORM entity, makes the Koa delete route a soft delete, keeps deleted rows out of reads, tests it, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-soft-delete/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 entity, the controller and the server before it changes a query. In an API laid out like javieraviles/node-typescript-koa-rest, `src/entity/user.ts` is one TypeORM entity, `User`, with a generated `id`, a `name` and an `email` validated by `class-validator`, plus a `userSchema` object the Swagger decorators read. `src/controller/user.ts` has six static handlers on `UserController`: `getUsers` calls `userRepository.find()`, `getUser` calls `findOne` by id, `createUser` and `updateUser` check for a duplicate email with `findOne`, `deleteUser` calls `userRepository.remove` after checking that the JWT's email matches the row, and `deleteTestUsers` removes every row whose email ends in `@citest.com`. `src/server.ts` opens the Postgres connection with `synchronize: true`, so the schema follows the entity on start, and `package.json` pins `typeorm` at `^0.2.32`, which has `@DeleteDateColumn`, `softRemove` and `withDeleted`. The unit tests in `tests/controller/user.test.ts` mock `typeorm` and `class-validator` with Jest and assert on `ctx.status` and `ctx.body`.

The entity gets one column: `@DeleteDateColumn({ type: 'timestamptz', nullable: true }) deletedAt: Date | null`. Because the connection uses `synchronize: true`, the column is added on the next start in development; for the deployed database the agent also writes a TypeORM migration under `src/migration/` that adds `deleted_at` and the index, and notes in the pull request that `synchronize` should be turned off once migrations are in use. `userSchema` does not list the new field, so the Swagger body for `POST /users` and `PUT /users/{id}` does not invite a client to set it.

The controller changes in two places. `deleteUser` calls `userRepository.softRemove(userToRemove)` instead of `remove`, so the row keeps its data and gets a timestamp, and still answers `204`. Reads need no change, because TypeORM's `find` and `findOne` exclude rows with a non-null delete date by default, which is the reason `@DeleteDateColumn` rather than a hand-written `deleted` boolean. The duplicate-email checks in `createUser` and `updateUser` are the subtle part: a deleted user's email would no longer be seen, so a new sign-up with that address would succeed and leave two rows. The agent passes `withDeleted: true` on those two `findOne` calls so a deleted email still blocks reuse, and says so in a comment. `deleteTestUsers` keeps a hard `remove`, since test rows are not customer data.

Two routes are added behind the JWT middleware: `GET /users/deleted`, which lists soft-deleted rows with `withDeleted: true` and `where: { deletedAt: Not(IsNull()) }`, and `POST /users/{id}/restore`, which calls `userRepository.recover` with the same email check `deleteUser` makes. The tests in `tests/controller/user.test.ts` gain cases for each: `deleteUser` expects `softRemove` on the mocked repository, `createUser` with a deleted email expects `400`, and `restore` expects `recover` and `200`. The agent runs `npm run lint`, `npm test` and `npm run build` the way `.github/workflows/ci.yml` does before opening the pull request.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add soft delete to this Koa API. Read src/entity/user.ts, src/controller/user.ts, src/server.ts, src/config.ts, src/protectedRoutes.ts, tests/controller/user.test.ts, package.json and .github/workflows/ci.yml first. Add a @DeleteDateColumn named deletedAt to the User entity and a TypeORM migration that adds the column and an index on it; leave userSchema without the field. Change deleteUser to softRemove, keep the JWT email check, and keep deleteTestUsers as a hard remove. Pass withDeleted: true on the duplicate-email findOne calls in createUser and updateUser with a comment saying why. Add GET /users/deleted listing soft-deleted rows and POST /users/{id}/restore calling recover with the same email check, both on the protected router with Swagger decorators. Extend tests/controller/user.test.ts for softRemove, the deleted-email conflict and restore. Run npm run lint, npm test and npm run build until they pass, then open a pull request that explains why reads need no change and which call keeps a hard delete.",
  "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/entity/user.ts`, `src/controller/user.ts` and `src/protectedRoutes.ts`, adds a migration under `src/migration/`, and extends `tests/controller/user.test.ts`. Its description explains that `find` and `findOne` exclude deleted rows on their own once the entity has a `@DeleteDateColumn`, which is why `getUsers` and `getUser` are untouched, and quotes the `npm test` and `npm run build` output from the sandbox.

It calls out the two decisions a reviewer most needs to see: the duplicate-email checks now look through deleted rows so an address cannot be reused while a soft-deleted account holds it, and `deleteTestUsers` still hard-deletes, with the reason beside each. The Swagger page at `/swagger-html` shows the two new routes with the descriptions the decorators carry.

Before merging, a reviewer decides whether `GET /users/deleted` should require more than a valid JWT, when soft-deleted rows should be purged for good and by which job (the hourly `CronJob` in `src/cron.ts` is one place to put it), and whether to turn off `synchronize` now that the schema has a migration.

## Run it on every entity that must keep deleted rows

A team with several Koa services on TypeORM sends this body once per repository from its own server, each `POST /o/{org}/sessions` with that repository in `resources` and a `request_id` that is a UUID v5 of the repository's full name, so a retried call returns the run already started. Each run reads its own entities: a service with relations gets `cascade: ['soft-remove']` on the owning side so children follow the parent, and one that already runs migrations instead of `synchronize` gets only the migration.

After the first merge, an automation on the Project with a `linear` trigger on `linear.issue.labeled`, `soft-delete` in `config.labels`, and the prompt "this issue names an entity that must keep deleted rows; add the column, switch its delete handler to softRemove, add the restore route and tests, and open a pull request" starts one run per labelled issue. The trigger adds the issue after the prompt and fills in nothing else.

## Why run it on Rush?

Soft delete looks like one annotation, and the annotation is the easy part. The real work is finding every query whose meaning changes: the uniqueness check that would let a deleted email be registered twice, the maintenance route that should still hard-delete, the reads that already do the right thing and must not be rewritten. The agent reads every call in the controller, makes each decision in a comment and a test, and runs the lint, test and build steps the workflow runs.

The test output and the build log stay with the run, so a reviewer sees the new cases pass against the mocked repository and the TypeScript compile succeed with the new column. A team with several services on the same pattern runs the request across all of them at once, each in its own sandbox.

## Frequently asked questions

### Why do the list and get routes not change?

TypeORM excludes rows whose `@DeleteDateColumn` is set from `find`, `findOne` and query builder results unless `withDeleted` is passed. `getUsers` and `getUser` use `find` and `findOne`, so they stop returning deleted users the moment the column exists, and the pull request keeps them as they are.

### Can a deleted user's email be registered again?

Not by default after this change. The duplicate checks in `createUser` and `updateUser` pass `withDeleted: true`, so a soft-deleted row still blocks its address. If the product wants the address freed, the comment beside each call shows the one line to remove.

### What about the schema in production?

The server runs with `synchronize: true`, which adds the column at start in development. The agent also writes a migration so a deployed database can be updated deliberately, and the pull request recommends turning `synchronize` off once migrations are in use, without doing it in the same change.

### Is anything still hard-deleted?

Yes, `DELETE /testusers`, which removes rows whose email ends in `@citest.com` after integration and load tests. Those are not customer records, so it keeps `remove`, and the pull request says so.

## More Koa jobs

- [Add Structured Logging to a Koa API](https://getrush.ai/run/add-structured-logging/koa/)
- [Fix Failing GitHub Actions Checks in a Koa API](https://getrush.ai/run/fix-failing-ci/koa/)
- [Move a Koa Project from Travis CI to GitHub Actions](https://getrush.ai/run/migrate-travis-to-github-actions/koa/)

## The same job on other stacks

- [Add Soft Delete to a Litestar App](https://getrush.ai/run/add-soft-delete/litestar/)
- [Add Soft Delete to a Mongoose Model](https://getrush.ai/run/add-soft-delete/mongoose/)
- [Add Soft Delete to a Prisma Schema](https://getrush.ai/run/add-soft-delete/prisma/)

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