#How does NestJS know which class to inject in what order?

11 messages · Page 1 of 1 (latest)

stiff river
#

E.g.

@Controller()
export class AppController {
  constructor(
    private readonly appService: AppService,
    private readonly playerService: PlayerService
  ) {}
}

The type is only specified as a TypeScript type which goes away at runtime, is there some custom compilation/additional parsing of typescript going on? Or something I'm missing?

#

I saw the javascript starter using @Dependencies to specify the types of deps, so I'm assuming there's a form of custom compilation/parsing typescript going on

manic pond
#

Under the hood, nestjs uses reflection metadata to handle the dependency injection.
I learned it by watching this video
https://www.youtube.com/watch?v=jo-1EUxMmxc

Ближайшая конференция: HolyJS 2022 Autumn, 10–11 ноября (Online), 20 ноября (Offline)
Подробности и билеты: https://bit.ly/3A5ruLp
— —
. . Kamil — автор NestJS. Он расскажет про подкапотные вещи и основные концепции NestJS. Что может быть интереснее, чем детальный разбор интересной и популярной технологии от её автора?

When Node.js came up for ...

▶ Play video
stiff river
# manic pond Under the hood, nestjs uses reflection metadata to handle the dependency injecti...

Yeah I understand how the decorator part works, but you have no knowledge of which type to inject in what order because that's not a thing in JavaScript, hence the need for the @Dependencies decorator. But in TypeScript you have compile time only type annotations which nestjs seems to somehow figure out either by parsing your source files or having a custom compilation step to extract that type

feral bluff
stiff river
feral bluff
#

Yes

stiff river
#

I see now, TIL thank you :)

feral bluff
#

This is the generally interesting part here:

let Foo = class Foo {
    constructor(foo) {
        this.foo = foo;
    }
};
Foo = __decorate([
    Injectable(),
    __metadata("design:paramtypes", [String])
], Foo);
export { Foo };
let Bar = class Bar {
    constructor(bar) {
        this.bar = bar;
    }
};
Bar = __decorate([
    Injectable(),
    __metadata("design:paramtypes", [String])
], Bar);
export { Bar };
let FooBar = class FooBar {
    constructor(foo, bar) {
        this.foo = foo;
        this.bar = bar;
    }
};
FooBar = __decorate([
    Injectable(),
    __metadata("design:paramtypes", [Foo, Bar])
], FooBar);
export { FooBar };
exotic loom