TypeOrm - How to use connection as standalone object with types?

VaL picture VaL · Feb 12, 2017 · Viewed 17.9k times · Source

Not working code just to illustrate what I'm trying to achieve

Some connection file

import { ConnectionManager } from 'typeorm';

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

using in some model

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

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

    @Column("int")
    sort: number;

    @Column()
    is_active: boolean;
}

later somewhere in the code I want to get connection with all methods something like that

import { connection } from 'someconnection';
import { AnnualIncome } from 'entities';

// some code here

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

Usually I'm getting an error from tsc that .getRepository() method was not found in connection. But if I do something like that:

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

the above code works with definitions and tsc does not complain about unexisting method. I'd like to avoid an extra definition connection.then() and get plain connection with all methods defined in <Connection> type

Thanks.

Answer

pleerock picture pleerock · Feb 12, 2017

just use createConnection method to create your connection when you bootstrap your application. Later you can access your connection from anywhere using getConnection() method:

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

Also you can simply use getRepository method also avalible from anywhere:

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

// some code here

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