如何为 TypeORM 指定 ormconfig.ts?

How to specify ormconfig.ts for TypeORM?

我使用 TypeORM CLI 创建了一个示例 TypeORM 项目,默认情况下 ormconfig.json:

{
   "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"
   }
}

这是目录结构:

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

这会在 database/migrations 文件夹中正确创建迁移并从中执行迁移。

我用下面的 ormconfig.ts 替换了 ormconfig.json :

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"
    }
};

然而,这会在根目录而不是 database/migrations 中创建迁移。

任何人都可以帮助我弄清楚这里缺少什么以及如何使用 ormconfig.ts 在预期目录中生成迁移吗?

在撰写本文时,TypeORM 仅查找 ormconfig.json 而忽略 ormconfig.ts。不过有work in progress支持。

除了 ormconfig.json 之外,您还需要在 package.json 中使用这些命令。

"typeorm": "ts-node -r tsconfig-paths/register ./node_modules/.bin/typeorm",
"migration:generate": "npm run typeorm -- migration:generate --config src/config/ormconfig.json --connection  --name ",
"migration:run": "npm run typeorm -- migration:run"

只需在导出时删除 default。 你的 ormconfig.ts 应该是这样的:

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,
};

在我的例子中,我使用的是 env.ts 主文件,因为数据库连接需要根据环境而有所不同。 另外,不要忘记使用 ts-node 来处理 package.json 中的 typeorm cli:

...
"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"
    ...
  }
...

所以创建、运行 或回滚迁移应该像这样:

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

嘿,我提出这个话题,因为我可以向你提出一个解决方案。

您可以将以下行放入 package.json 文件中:

"typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config server/environments/database.ts",

并且您的 ts 配置必须通过这样做直接导出配置:

export = { /* your config */ };

如您所见,您还可以指定配置的路径。您的配置无需位于项目的根级别。

希望对你有所帮助

项目结构

.
├── src // Typescript files
│   ├── entities
│   │   └── User.ts
│   ├── db
│   │   └── ormconfig.ts
│   │   ├── migrations
│   │   │   └── ... // migration files
├── tsconfig.json
├── package.json

要求

  • Typeorm 应该可以使用 src/db/ormconfig.ts 文件进行连接。
  • 我们应该能够创建 migrations,并使用 src/db/ormconfig.ts 文件执行所有 typeorm cli 支持的操作。

可能性

我们可以使用 ts-node 可用于 typescript 的包来完成此操作。

解与GithubLink

请查看 https://github.com/devjayantmalik/sample-node-typeorm 以获取完整示例。

Contents of src/db/ormconfig.ts file are:

import path from "path";
import { ConnectionOptions } from "typeorm";

export default {
  name: "default",
  type: "better-sqlite3",
  database: ":memory:",
  synchronize: true,
  migrationsRun: true,
  dropSchema: false,
  entities: [path.join(__dirname, "..", "entities", "**", "*.*"), path.join(__dirname, "..", "entities", "*.*")],
  migrations: [path.join(__dirname, "migrations", "*.*")],
  cli: {
    entitiesDir: path.join(__dirname, "..", "entities"),
    migrationsDir: path.join(__dirname, "migrations")
  }
} as ConnectionOptions;

Script section of src/db/package.json file are:

"scripts": {
  "dev": "ts-node-dev src/index.ts",
  "build": "tsc",
  "start": "node dist/index.js",
  "typeorm": "ts-node ./node_modules/.bin/typeorm -f ./src/db/ormconfig.ts",
  "migration:generate": "yarn run typeorm migration:generate -n",
  "migration:blank": "yarn run typeorm migration:create -n"
},```

## Usage

```bash
# Generate a blank migration
yarn migration:blank migration-name-here

# Generate migrations from database and entities.
yarn migration:generate

# Roll back a migration using cli options.
yarn typeorm migration:down

解决方案

指定ormconfig.ts

import { ConnectionOptions } from 'typeorm';

// Check typeORM documentation for more information.
const config: ConnectionOptions = {
    type: 'postgres',
    host: process.env.SQL_IP, // localhost
    port: process.env.SQL_PORT,// 5432
    username: process.env.SQL_USER, // databse login role username
    password: process.env.SQL_PASSWORD, // database login role password
    database: process.env.SQL_DATABASE, // db name

    // entities name should be **.entity.ts
    entities: [__dirname + '/**/*.entity{.ts,.js}'],

    // We are using migrations, synchronize should be set to false.
    // synchronize: process.env.TYPEORM_SYNCHRONIZE
    //  ? process.env.TYPEORM_SYNCHRONIZE.toLowerCase() === 'true'
    //  : false,
    synchronize: false,

    // Run migrations automatically,
    // you can disable this if you prefer running migration manually.
    migrationsRun: false,

    logging: false,
    // logger: 'advanced-console',

    // Allow both start:prod and start:dev to use migrations
    // __dirname is either dist or src folder, meaning either
    // the compiled js in prod or the ts in dev.
    migrations: [__dirname + '/migrations/*{.ts,.js}'],
    cli: {
        // Location of migration should be inside src folder
        // to be compiled into dist/ folder.
        migrationsDir: 'src/database/migrations'
    }
};

export = config;


在 Package.json 脚本下定义这个

"typeorm": "ts-node --files -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config src/database/config.ts"
"db:migrate": "npm run typeorm migration:run",
"db:create-migration": "npm run typeorm migration:create -- -n",

如果您使用带有 PnP 的 Yarn 2 作为包管理器,那么您不能像这里的其他解决方案那样做,因为您没有 node_modules 目录。

以下是我如何让它发挥作用的:

package.json

{
  "scripts": {
    "typeorm": "yarn node -r ts-node/register/transpile-only $(yarn bin typeorm)",
    "generate-migration": "yarn typeorm --config ormconfig.ts migration:generate --check",
  }
  "dependencies": {
     "typeorm": "^0.2.41",
  }
  "devDependencies": {
    "ts-node": "^10.4.0",
  }
}

ormconfig.ts

/* eslint-disable no-process-env */
import dotenv from 'dotenv';
import { SnakeNamingStrategy } from 'typeorm-naming-strategies';

dotenv.config();
dotenv.config({ path: './.env.local' });

export = {
  type: 'postgres',
  host: process.env.DB_HOST,
  port: process.env.DB_PORT,
  username: process.env.DB_USERNAME,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
  entities: ['src/infrastructure/persistence/**/*.entity.ts'],
  migrations: ['src/infrastructure/persistence/migrations/**/*.{ts,js}'],
  cli: {
    migrationsDir: 'src/infrastructure/persistence/migrations',
  },
  namingStrategy: new SnakeNamingStrategy(),
};

花了很长时间,但这对我有用 - 构建以将 TS 代码编译为 dist 文件并节点到 运行 它。 ts-node 不想和我的项目一起玩,我认为这很干净。 nodemon 用于 运行 在开发中使用它 - 虽然我认为我需要为此添加 ts-node / 仍然可以计算出编译和 运行.

ormconfig.ts

import { ConnectionOptions } from 'typeorm';    
export const baseConfig: ConnectionOptions = {
      synchronize: true, // TODO turn false after initial setup i.e. when moving to migrations
      type: 'mysql',
      host: 'localhost',
      port: 3306,
      username: 'xxx',
      password: 'xxx',
      database: 'xxx',
      entities: ['dist/Entities/**/**.entity.js'],
      migrations: ['dist/Migrations/*.js'],
      cli: {
        entitiesDir: 'dist/Entities/**/*.js',
        migrationsDir: 'dist/Migrations/*.js'
      }
    };

和package.json 脚本

  "scripts": {
    "build": "rimraf ./dist && tsc",
    "start": "npm run build && node dist/index.js",
    "dev": "nodemon src/index.ts",
    "format:prettier": "prettier --config .prettierrc 'src/**/*.ts' --write",
    "lint": "eslint . --ext .ts",
    "lint:fix": "eslint . --ext .ts --fix",
    "test": "jest --runInBand"
  },

就我而言,我根据 omrconfig.ts

更改了 omrconfig.json

然后我安装了 typeorm CLI global

npm i -g typeorm

并在package.json中添加两个脚本,第一个是:

"typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config server/environments/migrations.ts"

第二个是:

"migrate:create": "typeorm migration:create \"./typeorm/migrations/"

所以我设法使用终端命令

将迁移保存在typeorm/migrations内的所选文件夹中

npm run migrate:create -n {migrationName}