I have been out in the wild looking for a good way to generate migrations with TypeORM in a monorepo setup with Nx as our tool to manage our monorepo.
Since nothing is complete without salt, right now NestJS is also kinda like salt for me :kidding:, I am gonna show it in a NestJS app.
Generating Migration Based on Your Entities
Our goal is to be able to execute a command like this in terminal: nx migration:gen appName --name init
And then it should automatically initialize our first migration. The very first migration usually is a very big one and probably you do not wanna write it yourself but rather automate it:
So I here assume I have a project in my monorepo named botprobe-nest. Inside its project.json I will do the following
After this you should have a file in this path: apps/appName/src/migrations/1733903076640-init.ts
Creating New Empty Migrations
Here again our goal is to be able to run this command to create new migration files: nx migration:create appName --name migrationName
Again assume you need to manually do the migration (stuff needs to be taken care of, things like backing up from a field before renaming it, or complex scenarios where you wanna break one table into multiple tables, etc).
I just use this as a helper function for my migrations and I still have my NestJS way of configuring TypeOrmModule. TBH it might get a little hairy since we are dealing with the same thing in two place but sometimes it is OK to just roll it out and see how things will end up. BTW if you have a better way of dealing with this lemme know in the comments (AFAIK my solution is not compliant to DRY Principle).
Nx will read the apps/botprobe-nest/.env by default. That is how I am not using something like dotenv and still have access to DATABASE_URL defined in my .env file. You can learn more about it here.
// Use it just for migrationimport{TypeOrmModuleOptions}from'@nestjs/typeorm';import{join}from'path';import{DataSource}from'typeorm';if (!process.env.DATABASE_URL){throw'UndefinedEnvironmentVariableDatabaseUrl';}constoptions={type:'postgres',url:process.env.DATABASE_URL,entities:['**/*.entity{.ts,.js}'],migrations:[join(__dirname,'migrations','*{.ts,.js}')],}satisfiesTypeOrmModuleOptions;exportdefaultnewDataSource(options);
GitHub Repo
In this repo, the typeorm directory is where you can find a working example.