Reputation: 38475
I have a nestjs app, and am writing some stand alone tasks to go along with it.
The documentation for standalone apps shows how to get instances of services i.e.
const app = await NestFactory.createApplicationContext(AppModule);
const tasksService = app.get(TasksService);
but doesn't show how to get a repository if I wanted to read/write to the db.
I've tried the obvious:
const repo = app.get(Repository<User>);
but this throws the compiler error "Value of type 'typeof Repository' is not callable. Did you mean to include 'new'?ts(2348)".
The examples online (and in the nestjs docs) use @InjectRepository but my standalone task doesn't have any which can use that, sadly.
How do I get a repository instance I can use to read/write to the db in a standalone nestjs script?
Upvotes: 0
Views: 1898
Reputation: 38475
FYI: Another answer to my question would be 'what exactly are you trying to do?' because all I wanted to do was query/insert entities, and in nestjs you can do that directly from the entity type itself.
i.e.
instead of
const repo = app.get(getRepositoryToken(User));
...
const users = repo.find()
I could just do
const users = User.find()
which saves some gnarly setup code, and removes some imports.
Upvotes: 0
Reputation: 6685
app.get
receives a token of the provider. Then, if you're trying to get some custom repository from @nestjs/typeorm
, just retrieve its token using getRepositoryToken(User)
thus,
const repo = app.get(getRepositoryToken(User));
should work
Upvotes: 4