簡體   English   中英

TypeOrm-如何將連接用作具有類型的獨立對象?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM