So I have just started using NestJS switching from Express.
In Express, everything was an Object, be it your top level App, Routers, Request, Response etc.
Everything is pretty much same in NestJS. It incorporates everything that Express has and many more features.
One thing I cannot understand why everything in Nest so class based?
What's the point of defining classes for everything? like for Controllers, Modules (routers), Middlewares, Consumer of that Middleware and so on.
I would be very much interested in knowing the exact philosophy and design pattern.
I'm gonna answer here as I can, but I'd love to discuss this more in depth on our Discord Server for a more friendly conversation instead of a giant wall of text.
So first of all, why not use classes? They're syntactic sugar over objects, and Typescript is structurally typed, so if it looks like a duck, walks like a duck, and quacks like a duck, it might as well be a duck.
The big reason that Nest uses classes everywhere though can be boiled down to one word: metadata. In Typescript, with decorators, we're able to get a ton of type metadata about our code, because we use classes. Objects themselves don't store this same metadata (at least not easily) and Typescript doesn't allow for decorators on functions or objects alone, it has to be a class.
So the big draw here is that if Nest want's to look for metadata, (which it should be so that it can instantiate everything for you) it needs to be class based. With that metadata, Nest is able to implement some metadata scanning and discovery patterns that allow it to traverse trees of data between the providers, modules, and controllers and figure out what class instances need to be injected where. This leaves you, the developer, the freedom of not needing to inject the dependencies yourself to follow an Inversion of Control pattern. It also makes following what this is a lot easier in a class based context, rather than an object based one.
This design pattern honestly comes from Angular as Nest was heavily inspired by it, and Angular in turn was inspired by other Enterprise architecture implementations like Java and C#. These strongly typed languages are already class based, so it made sense for Google and the Angular Team to follow a similar structure for the design pattern. And because Angular did it, Nest followed suit a few years ago.
So, in short, Nest is class based because it works off of decorator metadata and Typescript decorators only work on classes. The design reasons came from Angular which is also classed based and uses decorators (which means it has to be class based), and decorators were implemented this way by the Typescript team because of design reasons from other languages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With