How to automate your database migrations with TypeORM in Node.js

Author:zhaoyiming0803 Date:2024-11-08

Working on Node.js and the frontend together, moving fast, always feels good.

Node.js has plenty of frameworks — Nest.js, Koa, Express… Nest.js is the one that looks most like Java’s Spring Boot: dependency injection, inversion of control… and it still keeps a JavaScript feel.

As for JS, I personally like functional programming. JS isn’t really an object-oriented language — it can only pretend to be one through prototypes. Even though ES6 gave us class, I still like plain functions, because functions are easy to combine, and writing them fits how JS actually works.

The Node.js framework I use most is Koa — small and powerful. Its middleware onion model chains all the functions together, and with async / await you get to decide when each function runs.

TypeORM docs: https://typeorm.io/

Any Node.js framework can use TypeORM. Here’s how:

Step 1: install typeorm with npm:

npm install typeorm --save-dev

Step 2: add the scripts to package.json

"typeorm": "typeorm-ts-node-commonjs",
"migration:create": "typeorm migration:create",
"migration:run-dev": "NODE_ENV=dev npx typeorm-ts-node-esm -d ./src/data-source.ts migration:run",
"migration:run-test": "NODE_ENV=test npx typeorm -d ./dist/data-source.js migration:run",
"migration:run-prod": "NODE_ENV=prod npx typeorm -d ./dist/data-source.js migration:run",

Step3: Config Data Source

// data-source.tsd
import { DataSource } from 'typeorm'
import { mysqlConfig } from './config'

export const DataSource = new DataSource({  
  type: 'mysql',  
  ...mysqlConfig,  // 只能通过 migration 手动同步数据库,不允许在这个地方同步  
  synchronize: false,            
  logging: false,  // 配置实体类路径  
  entities: [__dirname + '/entity/*.entity{.ts,.js}'],  // 配置 migrate 脚本路径  
  migrations: [__dirname + '/migration/*{.ts,.js}'],  
  charset: 'utf8'
})

export function initORM () {  
   return DataSource.initialize()    
      .then(() => {      
          console.log('Data Source has been initialized!')    
      })    
      .catch((error) => {         
          console.error('Error during Data Source initialization', error)    
      })
}