如何将连接用作具有类型的独立对象?

How to use connection as standalone object with types?

没有工作代码只是为了说明我正在努力实现的目标

一些连接文件

import { ConnectionManager } from 'typeorm';

const c = new ConnectionManager();
// user ormconfig.conf file
export const connection = c.createAndConnect();

在某些模型中使用

@Entity()
@Table("annual_incomes")
export class AnnualIncome
{
    @PrimaryGeneratedColumn()
    id: number;

    @Column({ length: 75 })
    variant: string;

    @Column("int")
    sort: number;

    @Column()
    is_active: boolean;
}

稍后在代码的某处,我想连接所有方法,例如:

import { connection } from 'someconnection';
import { AnnualIncome } from 'entities';

// some code here

api.get('/incomes', async(ctx) => {
    ctx.body = await connection.getRepository(AnnualIncome).find();
});

通常,我从 tsc 收到一个错误,即 .getRepository() 方法在 connection 中找不到。但是,如果我做类似的事情:

import { connection } from 'someconnection';
import { AnnualIncome } from 'entities';

// some code here

api.get('/incomes', async(ctx) => {
    ctx.body = await connection.then(async connection => {
       return await connection.getRepository(AnnualIncome).find();
    }
});

以上代码适用于定义,tsc 不会抱怨不存在的方法。

我想避免额外的定义 connection.then() 并使用在 <Connection> 类型中定义的所有方法得到简单的 connection

当您 bootstrap 您的应用程序时,只需使用 createConnection 方法创建您的连接。稍后您可以使用 getConnection() 方法从任何地方访问您的连接:

import { AnnualIncome } from 'entities';
import { createConnection, getConnection } from 'typeorm';

// somewhere in your app, better where you bootstrap express and other things
createConnection(); // read config from ormconfig.json or pass them here

// some code here

api.get('/incomes', async(ctx) => {
    ctx.body = await getConnection().getRepository(AnnualIncome).find();
});

您也可以简单地使用 getRepository 方法,也可以从任何地方使用:

import { AnnualIncome } from 'entities';
import { getRepository } from 'typeorm';

// some code here

api.get('/incomes', async (ctx) => {
    ctx.body = await getRepository(AnnualIncome).find();
});