如何将Connection用作带类型的独立对象? [英] How to use connection as standalone object with types?
本文介绍了如何将Connection用作带类型的独立对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
不工作代码只是为了说明我要实现的目标
一些连接文件
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
类型中定义的所有方法。
推荐答案
只需在引导应用程序时使用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();
});
这篇关于如何将Connection用作带类型的独立对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文