[英]TypeOrm - 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
收到一個錯誤,指出在connection
找不到.getRepository()
方法。 但是,如果我做這樣的事情:
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
謝謝。
引導應用程序時,只需使用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
方法, getRepository
方法也可以在任何地方使用:
import { AnnualIncome } from 'entities';
import { getRepository } from 'typeorm';
// some code here
api.get('/incomes', async (ctx) => {
ctx.body = await getRepository(AnnualIncome).find();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.