how to specify ormconfig.ts for typeorm?

Hussain Ali Akbar picture Hussain Ali Akbar · Sep 5, 2018 · Viewed 21k times · Source

I have created a sample typeorm project using the typeorm cli which has ormconfig.json by default:

{
   "type": "postgres",
   "host": "localhost",
   "port": 5432,
   "username": "postgres",
   "password": "postgres",
   "database": "test",
   "synchronize": false,
   "entities": [
      "src/entity/**/*.ts"
   ],
   "migrations": [
      "database/migrations/**/*.ts"
   ],
   "subscribers": [
      "src/subscriber/**/*.ts"
   ],
   "cli": {
      "entitiesDir": "src/entity",
      "migrationsDir": "database/migrations",
      "subscribersDir": "src/subscriber"
   }
}

this is the directory structure:

-database
  -migrations
-src
  -entity
-ormconfig.json

This creates the migrations in the database/migrations folder properly as well as executes the migrations from it.

I replaced ormconfig.json with the following ormconfig.ts :

export default {
    type: 'postgres',
    host: 'localhost',
    port: 5432,
    username: 'postgres',
    password: 'postgres',
    database: 'test',
    synchronize: false,
    "entities": [
        "src/entity/**/*.ts"
    ],
    "migrations": [
         "database/migrations/**/*.ts"
    ],
    "subscribers": [
        "src/subscriber/**/*.ts"
    ],
    "cli": {
        "entitiesDir": "src/entity",
        "migrationsDir": "database/migrations",
        "subscribersDir": "src/subscriber"
    }
};

this however creates migrations in the root directory instead of inside database/migrations.

Can anyone help me in figuring out whats missing here and how i can use ormconfig.ts to generate migrations inside the intended directory?

Thanks!

Answer

Siipe picture Siipe · Jul 5, 2019

Just remove the default while exporting. Your ormconfig.ts should be something like:

import env from './src/env';

export = {
  host: env.DB_CONFIG.host,
  type: 'mysql',
  port: env.DB_CONFIG.port,
  username: env.DB_CONFIG.username,
  password: env.DB_CONFIG.password,
  database: env.DB_CONFIG.database,
  entities: [
    'src/**/**.entity{.ts,.js}',
  ],
  migrations: [
    'src/database/migrations/*.ts',
  ],
  cli: {
    migrationsDir: 'src/database/migrations',
  },
  synchronize: false,
};

In my case I'm using a main env.ts file, as the database connection needs to be different depending on the environment. Also, don't forget using ts-node for dealing with typeorm cli in package.json:

...
"scripts": {
    ...
    "migrate:create": "ts-node ./node_modules/typeorm/cli.js migration:create -n",
    "migrate:up": "ts-node ./node_modules/typeorm/cli.js migration:run",
    "migrate:down": "ts-node ./node_modules/typeorm/cli.js migration:revert"
    ...
  }
...

So creating, running or rolling back migrations should be like:

npm run migrate:create FileName
npm run migrate:up
npm run migrate:down