Configuration

Depending on the package manager you have, you can use any of the following commands.

To perform this configuration we need to install the following dependencies.

Dotenv: This a dependency module that loads environment variables.

npm install dotenv

Typeorm naming strategies: This package provides some useful custom naming strategies on our database columns.

npm install typeorm-naming-strategies

You need to modify the src/app.module.ts file where the connection to the database is made, where a dynamic route is added to read the entities and migrations that are added.

@Module({
  imports: [
    ...
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async (configService: ConfigService) => {
        const dbConfig = configService.get<DatabaseConfig>('db');
        return {
          type: 'postgres',
          autoLoadEntities: false,
          namingStrategy: new SnakeNamingStrategy(),
          entities: [__dirname + '/../**/*.entity.{js,ts}'],
          migrations: [__dirname + '../src/migrations/*.{js,ts}'],
          ...dbConfig,
        };
      },
    }),
    ....
  ],
  ....
})

To use migrations with TypeORM version 0.3.0 or higher, you need to create an ormconfig.ts file at the root of the project.

In the ormconfig.ts file, add the following configuration.

This example configuration was done with a Postgres database, but you can also use other database types.

You can see more options on the datasource at this link.

import 'reflect-metadata';
import { DataSource } from 'typeorm';
import * as dotenv from 'dotenv';
import { SnakeNamingStrategy } from 'typeorm-naming-strategies';

let environment;

if (process.env.NODE_ENV === undefined) {
  environment = dotenv.config({ path: `.env.development` }).parsed;
}

const dataSource = new DataSource({
  type: 'postgres',
  schema: 'public',
  host: environment ? environment.DB_HOST : process.env.DB_HOST,
  port: Number(environment ? environment.DB_PORT : process.env.DB_PORT),
  username: environment ? environment.DB_USERNAME : process.env.DB_USERNAME,
  password: environment ? environment.DB_PASSWORD : process.env.DB_PASSWORD,
  database: environment ? environment.DB_DATABASE : process.env.DB_DATABASE,
  synchronize: false,
  logging: false,
  entities: ['src/**/*.entity{.ts,.js}'],
  migrations: ['src/migrations/*{.ts,.js}'],
  migrationsRun: true,
  namingStrategy: new SnakeNamingStrategy(),
});

export default dataSource;

When you start your project, you should have your env files defined. Otherwise, by default it looks for an .env.development file to read the environment variables from, but you can change the name of this file in your configuration.

At the time this was done, some TypeORM documentation configuration was found to be outdated, and some elements of the datasource were no longer allowed. So if you have problems configuring your datasource, you can check in the TypeScript class which fields are allowed.

Now add the following scripts to your package.json file.

{
 ...
 "typeorm": "ts-node  -r tsconfig-paths/register ./node_modules/typeorm/cli.js",
 "migrations:create": " f() { yarn typeorm migration:create src/migrations/\"$@\"; }; f",
 "migrations:run": "yarn typeorm migration:run -d ormconfig.ts",
 "migrations:show": "yarn typeorm migration:show -d ormconfig.ts",
 "migrations:rollback": "yarn typeorm migration:revert -d ormconfig.ts"
}

If you are using npm, you should use this configuration in your package.json file.

package.json

{
.....
"typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js",
"migrations:create": " f() { npm run typeorm migration:create src/migrations/\"$@\"; }; f",
"migrations:run": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js -d ormconfig.ts migration:run",
"migrations:show": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js -d ormconfig.ts migration:show",
"migrations:rollback": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js -d ormconfig.ts migration:revert"
}

Last updated