Logo

dev-resources.site

for different kinds of informations.

Nx + TypeORM + NestJS + Migrations

Published at
12/11/2024
Categories
typeorm
nestjs
nx
monorepo
Author
kasir-barati
Categories
4 categories in total
typeorm
open
nestjs
open
nx
open
monorepo
open
Author
12 person written this
kasir-barati
open
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


monorepo Article's
30 articles in total
Favicon
Creating a scalable Monorepo for Vue - Workspaces
Favicon
Creating a scalable Monorepo for Vue - Intro
Favicon
Unlocking the Power of Modern Web Architecture: Monorepos, Micro-Frontends, and Vite 🚀✨
Favicon
Emerging Trends in Git: GitOps, Monorepos, Distributed Repositories, and AI Integration
Favicon
Using Node's built-in test runner with Turborepo
Favicon
Building a Scalable Monorepo with TurboRepo
Favicon
Cookiecutter for fast starting with polylith
Favicon
Monorepo vs Microservices: Finding the Perfect Fit for Your Project
Favicon
Nx + TypeORM + NestJS + Migrations
Favicon
How to Build a Changelog Feature in React for Your App
Favicon
Convert a ReactJS app from Vite to Nx
Favicon
How to deploy Google Cloud Functions with PNPM workspaces
Favicon
How CodeMirror v6 dev setup installs packages without a monorepo
Favicon
How CodeMirror v6 dev setup retrieves packages without a monorepo
Favicon
Nx 20: Exploring the new TS preset and TypeScript project references
Favicon
Simple hello world program using Bazel and Go lang
Favicon
A practical example of shared libraries in a monorepo
Favicon
🗂️ Monorepo vs. Polyrepo: Choosing the Right Strategy for Your Projects 🚀
Favicon
Turborepo vs Nx: Mana yang Terbaik untuk Monorepo?
Favicon
Turborepo vs Nx: Which Monorepo Tool is Right for You?
Favicon
Optimizing +200 Pipelines of a Monorepo
Favicon
GitHub Actions: run a job only if a package has changed
Favicon
Building a Solid Foundation: Bootstrapping with Turbo Repo
Favicon
Nestjs Workspaces to build Monorepo
Favicon
Installing EmberJS v2 addons from GitHub forks using PNPM
Favicon
Understanding Monorepo
Favicon
Build Containerized MERN App with Lerna Monorepo
Favicon
Advanced monorepo management with Turborepo 2.0
Favicon
Vite config reuse
Favicon
Monorepo VS Polyrepo

Featured ones: