13

不工作的代码只是为了说明我想要实现的目标

一些连接文件

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>

4

1 回答 1

38

只需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();
});
于 2017-02-12T16:30:30.560 回答