2017-02-12 26 views
0

ちょうど私がどこかに私は接続を取得するコードでTypeOrm - タイプを持つスタンドアロンオブジェクトとしての接続の使い方

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

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

    @Column("int") 
    sort: number; 

    @Column() 
    is_active: boolean; 
} 

後のいくつかのモデルに使用して

いくつかの接続ファイル

import { ConnectionManager } from 'typeorm'; 

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

を達成しようとしているものを説明するためにコードを動作していませんすべての方法でそのようなものがあります。

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はunexisting方法文句はありません。 私は、余分な定義connection.then()を避け、<Connection>タイプ

おかげで定義されたすべてのメソッドで、プレーンconnectionを取得したいのですが。

答えて

3

createConnectionメソッドを使用すると、アプリケーションをブートストラップするときに接続を作成できます。

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

// some code here 

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

ありがとう:

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(); }); 

また、あなたは、単にどこからでもまたavalible getRepositoryメソッドを使用することができます。後で、どこでもgetConnection()メソッドを使用してからお使いの接続にアクセスすることができます。 'getRepository()'だけを使用すると接続名 'await getRepository(AnnualIncome、 'default') ' – VaL

+0

を設定しなければならないことに気づきたいのですが、実際にはデフォルトで' default'なので接続名パラメータは省略できます。あなたの名前が特定の接続名 – pleerock

+0

の場合、定義やバージョンが 'https:// github.com/typeorm/typeorm/blob/master/src/index.ts#L259'の間に衝突している可能性があります。バージョン '0.0.8'で私のために働いています。私のnpmパッケージでは、' https:// github.com/typeorm/typeorm/blob/master/src/index.ts#L269' – VaL

関連する問題