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

Express路由中如何传入已初始化的TypeORM实例对象

TypeORM实例全局路由访问实现方案

你可以选择以下任意一种方式实现REST路由层的appDataSource.manager访问,两种方案都兼容你现有的Apollo GraphQL注入逻辑。


方案1:全局中间件挂载到请求对象(推荐,架构对齐GraphQL注入逻辑)

这种方式和你给Apollo配置context的思路一致,把实例挂载到请求对象上,后续扩展请求级事务、动态数据源切换更方便。

  • 首先扩展Express的Request类型,避免TypeScript类型报错,可以在index.ts顶部或者项目全局类型声明文件中添加:
import { EntityManager } from 'typeorm';

declare global {
  namespace Express {
    interface Request {
      em: EntityManager;
    }
  }
}
  • 在注册业务路由之前添加全局中间件,将EntityManager注入到每个请求对象中:
const app = express();

app.use(express.json());
// 新增全局注入中间件,注意要放在路由注册之前
app.use((req, res, next) => {
  req.em = appDataSource.manager;
  next();
});

// 再注册业务路由
app.use('/kyc', kycRouter);
  • 在任意路由处理函数中,直接从req对象上获取实例使用即可:
// kycRouter内路由示例
kycRouter.get('/pending', async (req, res) => {
  const pendingList = await req.em.find(KycRecord, {
    where: { status: 'pending' }
  });
  res.json({ code: 0, data: pendingList });
});

方案2:直接导出实例在路由文件中导入使用

这种方式写法更简单,不需要额外写中间件,适合不需要做请求级扩展的场景。你的现有启动逻辑已经保证initialize()在服务启动前执行完成,不会出现实例未初始化的问题。

  • 确保appDataSource从独立的数据源配置文件导出,比如src/data-source.ts:
import { DataSource } from 'typeorm';

export const appDataSource = new DataSource({
  // 你的数据库配置项
  type: 'postgres',
  host: 'localhost',
  port: 5432,
  username: 'db_user',
  password: 'db_pass',
  database: 'your_db',
  entities: [__dirname + '/entities/**/*.{ts,js}'],
  migrations: [__dirname + '/migrations/**/*.{ts,js}'],
  synchronize: false,
});
  • 在需要使用的路由文件中直接导入即可调用:
// kyc路由文件
import { Router } from 'express';
import { appDataSource } from './data-source';
import { KycRecord } from './entities/KycRecord';

const kycRouter = Router();

kycRouter.get('/pending', async (req, res) => {
  const pendingList = await appDataSource.manager.find(KycRecord, {
    where: { status: 'pending' }
  });
  res.json({ code: 0, data: pendingList });
});

export default kycRouter;

你现有的Apollo Server context配置已经可以正常在Resolver中通过ctx.em访问EntityManager,不需要额外调整。

内容的提问来源于stack exchange,提问作者sev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 17:27:32