TypeORM documentation states that Generally, you call initialize method of the DataSource instance on application bootstrap, and destroy it after you completely finished working with the database. In practice, if you are building a backend for your site and your backend server always stays running - you never destroy a DataSource.
I am initializing exported DataSource on Electron main process with app.whenReady() in the application bootstrap.
data-source.ts
export const dbContext = new DataSource({
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'xxxxx',
password: 'xxxxx',
database: 'xxxxx',
synchronize: false,
logging: true,
entities: [User],
migrations: [InitialMigration1691999000003],
});
function in whenReady()
await dbContext.initialize();
await dbContext.runMigrations();
console.log("DB Connection Status", dbContext.isInitialized)
As I initialized the data source connection in the main process (application start), I should be able to use it in preload context bridge without initializing again as it is exported.
Accessing the data source through context bridge in preload script gives error. Uncaught (in promise) Error: No metadata for "User" was found
This is how I call the data source:
contextBridge.exposeInMainWorld('userRepository', {
getUserAsync: async (userName: string) => {
const userRepository = dbContext.getRepository(User);
const user = await userRepository.findOne({where: {userName}});
return user;
},
});
It does work fine if I check if data source is initialized before db calls. Should I use .destroy() method in the end of the methods as well? However, documentation says that Destroys the DataSource and closes all database connections. Usually, you call this method when your application is shutting down. However, I do not think this is a correct usage.
contextBridge.exposeInMainWorld('userRepository', {
getUserAsync: async (userName: string) => {
if (!dbContext.isInitialized) {
await dbContext.initialize();
}
const userRepository = dbContext.getRepository(User);
const user = await userRepository.findOne({where: {userName}});
return user;
},
});
| Dependency | Version |
|---|---|
| Node.js version | 18.12.1 |
| Typescript version | 5.1.6 |
| TypeORM version | 0.3.17 |
| Electron version | 25.4.0 |