# Add Seed Data to a NestJS TypeORM App

Yes. An agent writes an idempotent TypeORM seed script for a NestJS app, fills users, articles, tags and follows through the entities, and opens a PR.

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

## What the agent does

The agent starts from how the app reaches its database. In a NestJS app laid out like lujakob/nestjs-realworld-example-app, `src/app.module.ts` calls `TypeOrmModule.forRoot()` with no arguments, so the connection comes from `ormconfig.json`, which `ormconfig.json.example` shows as MySQL on `localhost:3306`, database `nestjsrealworld`, `entities: ["src/**/**.entity{.ts,.js}"]` and `synchronize: true`, meaning tables are created from the entities at startup and there are no migrations. `package.json` pins `typeorm ^0.2.24`, `@nestjs/typeorm ^7.0.0`, `mysql ^2.18.1`, `argon2`, `slug` and `ts-node ^8.9.1`; `index.js` registers ts-node and loads `src/main`, which is what `npm start` runs; `nodemon.json` watches `src`. There is no seed, fixture or script that creates data, and `README.md` only describes creating the empty database.

Then it reads the entities, because the seed has to produce rows the services can read back. `UserEntity` has `username`, `email`, `bio`, `image` and `password`, hashes the password with argon2 in a `@BeforeInsert` hook, a `favorites` many-to-many with a `@JoinTable`, and `articles` one-to-many. `ArticleEntity` has `slug`, `title`, `description`, `body`, `created` and `updated` timestamps, `tagList` as a `simple-array`, `author`, an eager `comments` relation and `favoriteCount`. `Comment` has `body` and `article`, `TagEntity` has `tag`, and `FollowsEntity` holds `followerId` and `followingId` as plain columns with no relation. `ArticleService.create` makes slugs with `slug(title, {lower: true})` plus a random base-36 suffix, `findAll` filters tags with `LIKE` on the simple-array column, and `favorite` keeps `favoriteCount` in step with the join table by hand. `UserService.create` refuses a duplicate username or email with a query builder check.

The script goes in `src/seed.ts` and runs with `npm run seed`, a new script that calls `ts-node src/seed.ts` the way `index.js` loads the app. It opens the connection with `createConnection()` so it reads the same `ormconfig.json`, then takes repositories with `getRepository`. It refuses to run when `NODE_ENV` is `production`. For a fixed list of demo users it finds by `username` and saves a `new UserEntity()` through `repository.save` only when missing, so the `@BeforeInsert` hook hashes the password and the accounts can sign in through `/api/users/login`; for articles it finds by a deterministic slug made with the same `slug` package and no random suffix, sets `tagList` and `author`, and adds its comments; it inserts each distinct tag into `TagEntity` once, each follow pair into `FollowsEntity` once, and sets `favoriteCount` to the number of favourite rows it wrote, matching what `favorite` would have produced. A second run finds everything and writes nothing.

To prove it, the agent installs MySQL with `apt-get` in its sandbox, creates the `nestjsrealworld` database, copies `ormconfig.json.example` and `src/config.ts.example` into place as the README says, runs `npm install`, then `npm run seed` twice and pastes both outputs, then queries the row counts of each table between runs. It starts the app with `npm start` and requests `/api/articles`, `/api/tags` and `/api/profiles/<username>` to show the seeded data through the real services, runs `npm test` for the existing `tag.controller.spec.ts`, and documents the command in the README's TypeORM section.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add development seed data to this NestJS TypeORM app. Read package.json, index.js, ormconfig.json.example, src/config.ts.example, src/app.module.ts, src/user/user.entity.ts, src/user/user.service.ts, src/article/article.entity.ts, src/article/comment.entity.ts, src/article/article.service.ts, src/tag/tag.entity.ts, src/profile/follows.entity.ts and README.md first. Write src/seed.ts that refuses to run when NODE_ENV is production, opens the connection with createConnection so it reads ormconfig.json, and for a fixed set of demo users, articles with tags and comments, tags and follow pairs creates each row only when it is absent: users by username through repository.save so the BeforeInsert hook hashes the password, articles by a deterministic slug made with the slug package, tags by name, follows by pair, with favoriteCount matching the favourite rows written. Add npm run seed with ts-node. Install MySQL in your sandbox, create the database, copy the two example config files, run the seed twice and paste both outputs with the table counts between runs, start the app and show /api/articles, /api/tags and one profile, run npm test, and document the command in the README. Change no entity and no service.",
  "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/seed.ts`, changes `package.json` for the `seed` script and the README's TypeORM section, and touches no entity, service or controller. Its description lists the demo users, articles, tags and follows the script writes, shows the first run creating them and the second run skipping every one with the table counts unchanged, and shows the `/api/articles`, `/api/tags` and profile responses served from the seeded rows.

The seeded accounts sign in through the existing `/api/users/login`, because the hook hashed their passwords on insert; the articles list and filter by tag through `findAll` exactly as user-created ones do, and `favoriteCount` agrees with the join table so `favorite` and `unFavorite` keep counting correctly from the seeded state. `synchronize: true` still creates the tables; the seed only fills them.

Before merging, a reviewer decides whether a deterministic slug without the random suffix is acceptable for demo rows or should mirror the service's suffix, reviews the demo content, and chooses whether `npm run seed` should also appear in a setup script or stay a manual step.

## Run it on every entity change merged

Add an automation to the Project with a prompt that asks the agent to read `src/seed.ts` against every `*.entity.ts` and update the seed for any new required column or relation, and give it a `github` trigger on `pull_request.closed.merged` with `branch_patterns` matching your main branch. Each merged pull request starts one run with the event after the prompt; the trigger fills in no placeholder, and only work by a repository owner, member or collaborator fires it, never a fork or a bot sender.

The run opens its own pull request when the seed needs a change and ends with a note when it does not. The automation's `max_runs_per_hour` holds a merge train to that many runs an hour, with a fire past it created `queued` until the hour has room. From your own server, the same run starts with this request and a `request_id` that is a UUID v5 of the merge commit's SHA, so a retried start returns the run already begun.

## Why run it on Rush?

A TypeORM seed is only right when it goes through the same hooks and relations the services use: a raw insert skips the password hash, a slug with the service's random suffix is never found again, and a favourite without its count drifts the first time someone clicks. The agent reads the entities and both services before writing, then runs the seed twice against a real MySQL in its own sandbox and reads the data back through the running app.

The transcript keeps the install, the two seed runs, the table counts and the API responses with their output, so a reviewer checks the diff and the evidence from one page. Several services on the same ORM can be seeded 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 repository.save instead of insert or a SQL file?

`UserEntity` hashes its password in a `@BeforeInsert` hook, and TypeORM runs entity hooks on `save` but not on `insert` or a query builder. A SQL file would need its own argon2 hashing and would break the first time an entity gained a column. Going through the entities keeps the seed and the app on one definition.

### How is the seed idempotent without unique constraints?

The entities declare no unique columns, so the script does the lookups itself: users by `username`, articles by their deterministic slug, tags by `tag`, follows by the `followerId` and `followingId` pair. Each write happens only when the lookup finds nothing, and the second run's unchanged table counts in the pull request are the proof.

### Does the seed depend on synchronize being on?

It expects the tables to exist, which `synchronize: true` in `ormconfig.json` arranges on the first app start; the script opens the connection through the same config, so running `npm run seed` on a fresh database also creates them. If you later switch to migrations, run them first; the script itself does not change.

### Will the seed run in production by mistake?

It stops when `NODE_ENV` is `production` before opening a connection, and it is a separate `npm run seed` command rather than part of `npm start`, so nothing in the deploy path calls it. The pull request shows the refusal's message.

## More TypeORM jobs

- [Add Slow Query Logging to a TypeORM + NestJS App](https://getrush.ai/run/add-slow-query-logging/typeorm/)
- [Add Soft Delete to TypeORM Entities](https://getrush.ai/run/add-soft-delete/typeorm/)
- [Wrap Multi-Step Writes in TypeORM Transactions](https://getrush.ai/run/add-transactions/typeorm/)

## The same job on other stacks

- [Add Seed Data to a Vapor App](https://getrush.ai/run/add-seed-data/vapor/)
- [Add Database Seeders to an AdonisJS API](https://getrush.ai/run/add-seed-data/adonisjs/)
- [Add Database Seeders to a CodeIgniter 4 App](https://getrush.ai/run/add-seed-data/codeigniter/)

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