如何从 nestjs 独立应用程序获取存储库实例
how do I get a repository instance from nestjs standalone app
我有一个 nestjs 应用程序,并且正在编写一些独立的任务来配合它。
独立应用程序的 documentation 展示了如何获取服务实例,即
const app = await NestFactory.createApplicationContext(AppModule);
const tasksService = app.get(TasksService);
但没有显示如果我想 read/write 到数据库如何获取存储库。
我试过显而易见的方法:
const repo = app.get(Repository<User>);
但这会引发编译器错误“'typeof Repository' 类型的值不可调用。您是要包含 'new' 吗?ts(2348)”。
在线示例(以及 nestjs 文档中的示例)使用 @InjectRepository 但遗憾的是,我的独立任务没有任何可以使用它的示例。
如何在独立的 nestjs 脚本中获取可用于 read/write 数据库的存储库实例?
app.get
收到提供商的令牌。然后,如果您尝试从 @nestjs/typeorm
获取一些自定义存储库,只需使用 getRepositoryToken(User)
检索其令牌
因此,
const repo = app.get(getRepositoryToken(User));
应该可以
仅供参考:我的问题的另一个答案是 'what exactly are you trying to do?' 因为我想做的只是 query/insert 个实体,而在 nestjs 中你可以直接从实体类型本身做到这一点。
即
而不是
const repo = app.get(getRepositoryToken(User));
...
const users = repo.find()
我可以做到
const users = User.find()
它节省了一些粗糙的设置代码,并删除了一些导入。
我有一个 nestjs 应用程序,并且正在编写一些独立的任务来配合它。
独立应用程序的 documentation 展示了如何获取服务实例,即
const app = await NestFactory.createApplicationContext(AppModule);
const tasksService = app.get(TasksService);
但没有显示如果我想 read/write 到数据库如何获取存储库。
我试过显而易见的方法:
const repo = app.get(Repository<User>);
但这会引发编译器错误“'typeof Repository' 类型的值不可调用。您是要包含 'new' 吗?ts(2348)”。
在线示例(以及 nestjs 文档中的示例)使用 @InjectRepository 但遗憾的是,我的独立任务没有任何可以使用它的示例。
如何在独立的 nestjs 脚本中获取可用于 read/write 数据库的存储库实例?
app.get
收到提供商的令牌。然后,如果您尝试从 @nestjs/typeorm
获取一些自定义存储库,只需使用 getRepositoryToken(User)
因此,
const repo = app.get(getRepositoryToken(User));
应该可以
仅供参考:我的问题的另一个答案是 'what exactly are you trying to do?' 因为我想做的只是 query/insert 个实体,而在 nestjs 中你可以直接从实体类型本身做到这一点。
即
而不是
const repo = app.get(getRepositoryToken(User));
...
const users = repo.find()
我可以做到
const users = User.find()
它节省了一些粗糙的设置代码,并删除了一些导入。