javascript - typeorm CLI 不会等待从 ormconfig.ts 导出的异步方法
Typeorm 应该能够像在这个文件中那样等待这个导出。并且在这个问题中也有说明。出于某种原因,它不起作用。
// src/db/ormconfig.ts
import {
Entity1, Entity2
} from '@entity/internal';
import { getSecret } from '@utils/SystemManager';
import Logger from '@utils/Logger';
const getConnectionOptions = async () => {
const USERNAME = await getSecret('username');
const PASSWORD = await getSecret('password');
const {
RDS_DB_INSTANCE_URL,
RDS_DB_INSTANCE_PORT,
RDS_DB_NAME,
} = process.env;
Logger.info(
'Username: (%s) Password: (%s) InstanceURL: (%s) InstancePort: (%s) DBName: (%s)',
USERNAME,
PASSWORD,
RDS_DB_INSTANCE_URL,
RDS_DB_INSTANCE_PORT,
RDS_DB_NAME,
);
const config = {
name: 'default',
type: 'postgres',
port: Number(RDS_DB_INSTANCE_PORT),
// this have to be false on production as it might drop the data
synchronize: false,
// migrationsRun: true,
logging: true,
host: RDS_DB_INSTANCE_URL,
username: USERNAME,
database: RDS_DB_NAME,
password: PASSWORD,
// TODO: set the naming strategy
// namingStrategy: new SnakeNamingStrategy(),
entities: [
Entity1, Entity2,
],
migrations: [`${__dirname}/migration/**/*.ts`],
subscribers: [`${__dirname}subscriber/**/*.ts`],
cli: {
entitiesDir: 'src/entity',
migrationsDir: 'src/migration',
subscribersDir: 'src/subscriber',
},
};
if (PASSWORD) {
Object.assign(config, {
password: PASSWORD,
});
}
return config;
};
module.exports = getConnectionOptions;
而我测试的命令是:
node --require ts-node/register --require tsconfig-paths/register ./node_modules/typeorm/cli.js --config ./src/db/ormconfig.ts
输出是:
Error during migration run:
TypeORMError: Cannot find connection default because its not defined in any orm configuration files.
at new TypeORMError (C:\Users\ahmed\Desktop\manjaro\src\error\TypeORMError.ts:7:9)
at ConnectionOptionsReader.<anonymous> (C:\Users\ahmed\Desktop\manjaro\src\connection\ConnectionOptionsReader.ts:56:19)
at step (C:\Users\ahmed\Desktop\manjaro\node_modules\typeorm\node_modules\tslib\tslib.js:143:27)
at Object.next (C:\Users\ahmed\Desktop\manjaro\node_modules\typeorm\node_modules\tslib\tslib.js:124:57)
at fulfilled (C:\Users\ahmed\Desktop\manjaro\node_modules\typeorm\node_modules\tslib\tslib.js:114:62)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
error Command failed with exit code 1.
经过一些调试并直接编辑 node_modules 中的 typeorm 代码库,我发现它使用的 connectionOptions 类型是“异步函数”,所以它没有等待它。有任何想法吗?
答案#1
在 typeorm#4149 中已解决,但引用如下:
// a.ts
const f = async () => {};
export f;
现在,
// b.ts
const f = await require('./a.ts');
事情是这样的,我正在导出方法本身并等待 require,假设它会调用该方法并等待它,然而情况并非如此。这会将一个“异步函数”传递给 typeorm。如果满足以下情况,这将会起作用:
// b.ts
const f = await require('./a.ts')();
但这需要在 typeorm 内部工作 # 失败
但是我们可以:
// a.ts
const f = async () => {};
export f();
调用 f,所以我们需要 f 的调用,而不是 f 本身,这样 await 才能在它上面工作。
