I would like to create a Wrapper (service or manager) to drive TypeORM for my app.
I encounter lot of issue and I think my wrapper badly manage connection of my database with TypeORM.
I created basic example that seems to be good but.... connection is not connected (but TypeORM says that a connection is automatically connected when is created)
My methods to create or get connection previously created :
getConnection(): Connection
{
if (!typeorm.getConnectionManager().has("default"))
{
this.createConnection()
.then((connection) => {return connection})
.catch((error) => {
console.log('create connection database failed')
dialog.showErrorBox('Error!', 'create connection database failed')
})
}
else
{
return typeorm.getConnectionManager().get("default")
}
}
my method for testing status connection :
status(): string
{
if (!typeorm.getConnectionManager().has("default"))
{
return "nothing (default) connection"
}
else
{
let isConnected = typeorm.getConnectionManager().get("default").isConnected
if (isConnected)
{
return "connected !"
}
else
{
return "not connected !"
}
}
}
and my createConnection method :
createConnection(): Promise<Connection>
{
return typeorm.createConnection({
name: 'default',
type: 'better-sqlite3',
database: './src/../data/database/mydb.db',
entities: [
xxxxx,
xxxxxx,
xxxxxx,
xxxxxx
],
synchronize: true
})
}
and this is a basic persist method with test example :
persist(entityObject: any): any
{
let connection = this.getConnection()
if (connection instanceof Connection)
{
dialog.showErrorBox('DEBUG', 'connection is instance of Connection')
}
else
{
dialog.showErrorBox('DEBUG', 'connection is not instance of Connection')
}
dialog.showErrorBox('Connection Status', this.status())
dialog.showErrorBox('Connection is connected ?', connection.isConnected.toString())
}
My connection variable is a good instance of Connection object TypeORM. But just after when I test if this connection is connected with this :
connection.isConnected.toString()
It return false.
and this :
this.status()
return me that connection is not connected
Very strange for me. I don't understand why and how manage connection into a wrapper class js. I think there is a little few tricks that I don't understand perhaps.
My logic process is : On each method of my wrapper class like Persist, update, select, etc... I test if connection ('default') exist. If yes a get this connection whereas I create connection. And after when I get Connection object I can launch my commands TypeORM into my database. Have I a good mentation ?