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


typeorm Article's
30 articles in total
Favicon
Creating Typescript app with decorator-based dependency injection 💉
Favicon
ORM and Migrating/Adding Data to MySql Database from MongoDb using TypeOrm in javaScript
Favicon
🌟 NestJS + Databases: Making Snake Case Seamless!🐍
Favicon
NestJS TypeORM and Multi-Tenancy
Favicon
Nx + TypeORM + NestJS + Migrations
Favicon
Handling TypeORM migrations in Electron apps
Favicon
How to manage multiple environments with dotenv and Databases config in NestJS
Favicon
Sveltekit + TypeScript + TypeORM + ESM
Favicon
Using TypeORM with TSX: A Smoother Development Experience
Favicon
Prisma or TypeORM ?
Favicon
Mock TypeORM Package
Favicon
Connecting a Serverless PostgreSQL Database (Neon) to NestJS Using the Config Service
Favicon
NestJS and TypeORM — Efficient Schema-Level Multi-Tenancy with Auto Generated Migrations: A DX Approach
Favicon
Getting Started with NestJS and TypeORM: A Beginner's Guide
Favicon
Migration - Module query with TypeORM version 0.3.x
Favicon
Double bind the foreign key to avoid unnecessary JOIN in TypeORM
Favicon
Handling Migrations on NestJS with TypeORM
Favicon
match all conditions in the first array and at least one condition for the second array typeorm
Favicon
Taming cross-service database transactions in NestJS with AsyncLocalStorage
Favicon
Announcing Version 2.0 of nestjs-DbValidator
Favicon
Optimizing SQL Queries by 23x!!!
Favicon
Building my own PostgresGUI with TypeORM+TypeGraphQl class generaion
Favicon
TypeORM | Query Builder
Favicon
NestJs에서 TypeORM을 사용하여 MySQL 연동, 2024-01-25
Favicon
Defining Custom Many-to-many Relationship in NestJS TypeORM.
Favicon
4. Building an Abstract Repository
Favicon
3. Building a Common Repository for Nest.js Microservices
Favicon
TypeORM - remove children with orphanedRowAction
Favicon
Migrating NestJS project with TypeORM to Prisma
Favicon
Authentication part 2 using NestJS

Featured ones: