Last active
October 27, 2019 18:28
-
-
Save DennisKo/bd3a6c849a00c937462071ef557748f9 to your computer and use it in GitHub Desktop.
TypeORM Connectio Manager
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Database { | |
private connectionManager: ConnectionManager; | |
private readonly options: ConnectionOptions = { | |
type: "postgres", | |
host: "localhost", | |
port: 5432, | |
username: "postgres", | |
password: "postgres", | |
database: "pony_dev", | |
entities: [Item], | |
synchronize: true, | |
logging: false | |
}; | |
constructor() { | |
this.connectionManager = getConnectionManager(); | |
} | |
connect = async (): Promise<Connection> => { | |
return await createConnection(this.options); | |
}; | |
public async getConnection() { | |
const CONNECTION_NAME = `default`; | |
let connection: Connection; | |
try { | |
if (this.connectionManager.has(CONNECTION_NAME)) { | |
console.log(`Using existing connection ...`); | |
connection = await this.connectionManager.get(CONNECTION_NAME); | |
if (!connection.isConnected) { | |
connection = await connection.connect(); | |
} | |
} else { | |
console.log(`Creating connection ...`); | |
connection = await createConnection(this.options); | |
} | |
return connection; | |
} catch (error) { | |
throw new Error(error); | |
} | |
} | |
} | |
export const dbConnect = async () => { | |
try { | |
const database = new Database(); | |
const dbConn: Connection = await database.getConnection(); | |
return dbConn; | |
} catch (error) { | |
throw new Error(error); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment