You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Electron中TypeORM主进程初始化数据源无法在预加载脚本调用问题

问题:Electron主进程初始化TypeORM DataSource后,预加载脚本调用时报元数据错误

背景

根据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.js18.12.1
TypeScript5.1.6
TypeORM0.3.17
Electron25.4.0

内容的提问来源于stack exchange,提问作者Melih Çoban

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 03:35:41