Search code examples
node.jstypeorm

How to use connection as standalone object with types?


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:

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. However if I do something like:

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 not-existing methods.

I'd like to avoid an extra definition connection.then() and get plain connection with all methods defined in <Connection> type.


Solution

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