Search code examples
javascripttypescripttypeorm

Cannot add cli parameters to DataSourceOptions in TypeORM


In the typeORM documentation a cli parameter can be added to DataSourceOptions according to https://github.com/typeorm/typeorm/blob/master/docs/data-source-options.md. The example I saw on https://typeorm.io/using-cli looks was

{
    cli: {
        entitiesDir: "src/entity",
        subscribersDir: "src/subscriber",
        migrationsDir: "src/migration"
    }
}

I tried this in my code as follows:

let dataSource = new DataSource(
  {
        type: 'postgres',
        host: 'localhost',
        port: 5432,
        database: 'website',
        username: 'test',
        password: 'test',
        logging: true,
        synchronize: false,
        entities: [User, Posts],
        cli: {
            entitiesDir: "src/entity",
            subscribersDir: "src/subscriber",
            migrationsDir: "src/migration"
        }
  })

However I get the following error: Argument of type '{ type: "postgres"; host: string; port: number; database: string; username: string; password: string; logging: true; synchronize: false; entities: (typeof User | typeof Wallet)[]; cli: { entitiesDir: string; subscribersDir: string; migrationsDir: string; }; }' is not assignable to parameter of type 'DataSourceOptions'. Object literal may only specify known properties, and 'cli' does not exist in type 'PostgresConnectionOptions'.ts(2345)


Solution

  • I had the same problem. To solve this issue, you can simply remove the cli key from the Datasource options and specify the path when creating a new migration

    typeorm migration:create -n UrlMigration -d src/migrations 
    

    -d option is used to specify the directory where your migration will be created

    "scripts": {
      ...
      "typeorm": "typeorm-ts-node-commonjs -d ormconfig.ts"
    }
    

    NB : Replace ormconfig.ts with your datasource filename

    refer to TypeORM CLI help

    Note: entities, migrations and subscribers can be added to the datasource options in the folowing way:

    // ormconfig.ts
    
    export const datasource = new DataSource({
      type: "postgres",
      host: "localhost",
      port: 5432,
      database: "database",
      username: "username",
      password: "password",
      entities: [EntityA, EntityB, EntityC],
      migrations: [__dirname + "/migrations/*{.js,.ts}"],
      subscribers: [],
    })