Electron中TypeORM主进程初始化数据源无法在预加载脚本调用问题
背景
根据TypeORM文档:
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
我在Electron主进程启动阶段,通过app.whenReady()初始化了导出的DataSource实例:
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], });
主进程whenReady()初始化逻辑
await dbContext.initialize(); await dbContext.runMigrations(); console.log("DB Connection Status", dbContext.isInitialized)
错误情况
按预期,主进程初始化完成后,应该能在预加载脚本的contextBridge中直接使用该数据源,无需再次初始化,但调用时抛出错误:
Uncaught (in promise) Error: No metadata for "User" was found
调用代码如下:
contextBridge.exposeInMainWorld('userRepository', { getUserAsync: async (userName: string) => { const userRepository = dbContext.getRepository(User); const user = await userRepository.findOne({where: {userName}}); return user; }, });
临时可行方案
若在每次数据库调用前检查数据源是否初始化,未初始化则执行initialize(),代码可正常运行:
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; }, });
疑问
但我不确定是否需要在方法末尾调用.destroy()?TypeORM文档说明:
Destroys the DataSource and closes all database connections. Usually, you call this method when your application is shutting down.
我认为这种场景下调用destroy并不合理,但希望确认这个判断是否正确。
依赖版本信息
| 依赖项 | 版本 |
|---|---|
| Node.js | 18.12.1 |
| TypeScript | 5.1.6 |
| TypeORM | 0.3.17 |
| Electron | 25.4.0 |
内容的提问来源于stack exchange,提问作者Melih Çoban

