DEV Community

Cover image for Nx + TypeORM + NestJS + Migrations

Nx + TypeORM + NestJS + Migrations

Hi,

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

apps/botprobe-nest/project.json

{
  // ...
  "targets": {
    // ...
    "migration:gen": {
      "executor": "nx:run-commands",
      "options": {
        "command": "ts-node --project tsconfig.app.json ../../node_modules/typeorm/cli migration:generate src/migrations/{args.name} --pretty -d src/data-source.ts",
        "forwardAllArgs": true,
        "cwd": "{projectRoot}"
      }
    },
    // ...
  },
  // ...
}
Enter fullscreen mode Exit fullscreen mode

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).

apps/botprobe-nest/project.json

{
  // ...
  "targets": {
    // ...
    "migration:create": {
      "executor": "nx:run-commands",
      "options": {
        "command": "../../node_modules/.bin/typeorm migration:create src/migrations/{args.name}",
        "forwardAllArgs": true,
        "cwd": "{projectRoot}"
      },
    },
    // ...
  },
  // ...
}
Enter fullscreen mode Exit fullscreen mode

After this you should have a file in this path: apps/appName/src/migrations/1733903076640-migrationName.ts

Running Migrations

Now its time to run our migrations with this command: nx migration:run appName.

To that end we need the following script in our project.json

apps/botprobe-nest/project.json:

{
  "targets": {
    "migration:run": {
      "executor": "nx:run-commands",
      "options": {
        "command": "ts-node --project tsconfig.app.json ../../node_modules/typeorm/cli migration:run -d src/data-source.ts",
        "cwd": "{projectRoot}"
      }
    },
  }
}
Enter fullscreen mode Exit fullscreen mode

apps/botprobe-nest/src/data-source.ts

Keep in mind that:

  1. 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).
  2. 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 migration
import { TypeOrmModuleOptions } from '@nestjs/typeorm';
import { join } from 'path';
import { DataSource } from 'typeorm';

if (!process.env.DATABASE_URL) {
  throw 'UndefinedEnvironmentVariableDatabaseUrl';
}

const options = {
  type: 'postgres',
  url: process.env.DATABASE_URL,
  entities: ['**/*.entity{.ts,.js}'],
  migrations: [join(__dirname, 'migrations', '*{.ts,.js}')],
} satisfies TypeOrmModuleOptions;

export default new DataSource(options);
Enter fullscreen mode Exit fullscreen mode

GitHub Repo

In this repo, the typeorm directory is where you can find a working example.

GitHub logo kasir-barati / nestjs-materials

NestJS tips, tricks, Notes, Things which are not in doc and I used to figure them out and use them







Follow me on:
Instagram: https://www.instagram.com/node.js.developers.kh/
Facebook: https://www.facebook.com/kasirbarati
X: https://x.com/kasir_barati
YouTube: https://www.youtube.com/@kasir-barati
GitHub: https://github.com/kasir-barati/
Dev.to: https://dev.to/kasir-barati
LinkedIn: https://linkedin.com/in/kasir-barati


Top comments (0)