0

I'm trying to get TypeOrm working, and instead of creating a connection in my index.ts file like the documentation suggests, I'd like to abstract the connection into its own class to be able to import it wherever I need it.

I'm using an ormconfig file for TypeOrm options. For some reason Typescript tells me that my connection getter in the class is missing a '(' and I cannot figure out why that is.

Any idea?

import { createConnection, Connection } from 'typeorm'

export class DatabaseConnection {

    private _connection: Connection;

    public get async connection(): Connection { // 'connection()' is underlined with the error message "expected '('"
        if (!this._connection) {
            this._connection = await createConnection()
        }

        return this._connection
    }
}
louis.sugar
  • 171
  • 9

1 Answers1

1

JavaScript does not support async getters and setters. You may just return the promise. Something like this:

import { createConnection, Connection } from 'typeorm'

export class DatabaseConnection {

    private _connection?: Promise<Connection>;

    public get connection(): Promise<Connection> {
        if (!this._connection) {
            this._connection = createConnection()
        }

        return this._connection
    }
}

There are workarounds like write an immediate executable function. This is an helpful read: https://medium.com/trabe/async-getters-and-setters-is-it-possible-c18759b6f7e4

A longer read is here as well: https://stackoverflow.com/a/44578144/298455

Nishant
  • 54,584
  • 13
  • 112
  • 127