My experience with NestJS,
If you have ever worked with NodeJS and if you don’t have a clear scalable architecture, you’ll end up with messy code, where everyone can add whatever he wants all over the place.
Also, besides the clear architecture, NestJS is compatible with Typescript for static types, If you wish not to use Typescript, NestJS will support your vanilla JS just fine.
Also, if you have ever worked with Angular or/and Spring Boot you’ll find it easier to use the framework, you’ll come across many of the familiar terms such as dependency injection, decorators, exception filters, pipes, guards and interceptors, DTOs, …etc. (we won't get into the definition of those terms, there're better ressources for that)
I’ll explain the fundamentals in nutshell, NestJS got a rich documentation for details.
To be noted, I'll be mostly comparing NestJS to Spring Boot framework, totally different languages but the they share common concepts.
Also, if you find similar sentences from official documentations here, yep, I might have copy pasted them.
@Controllers.
Controllers are responsible for handling incoming requests and returning responses to the client.
If you’re coming from a Spring Boot background, that’s the same thing @RestController.
In order to create a user route to list users and create a user. Our code will be:
NestJS:
@Controller('users')
export class UserController {
@Get()
findAll(): string {
return 'This action list of users';
}
@Post()
findAll(): string {
//Call service to handle user creation.
return 'This action creates a new user';
}
}
Equivalent in Spring Boot:
@RestController
@RequestMapping("/users")
public class UserController {
@GetMapping
public String getUsers(){
return "This action list of users";
}
@PostMapping
public String createUser(){
//Call service to handle user creation.
return "This action creates a new user";
}
}
Note that, you can generate controller using, nest generator: nest g controller users
@Providers & @Services.
Providers are a fundamental concept in Nest. Many of the basic Nest classes may be treated as a provider – services, repositories, factories, helpers, and so on.
Here is an example of using a UserService in which we inject our Repository that deals with our database and provide us the needed functions.
NestJS:
@Injectable()
export class UserService {
constructor(
@InjectRepository(User)
private readonly userRepository: Repository<User>,
) {}
findAllUsers(): Promise<User[]> {
return this.userRepository.find();
}
}
Equivalent in Spring Boot:
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public List<User> findAllUsers(){
return userRepository.findAll();
}
}
Note that, you can generate controller using, nest generator: nest g service users
@Modules
Modules are a closer concept to Angular than it's to Spring boot, NestJS uses this concept to organize application structure.
NestJS:
import { Module } from '@nestjs/common';
import { UserController } from './user.controller';
import { UserService } from './user.service';
@Module({
controllers: [UserController],
providers: [UserService],
})
Equivalent in Spring Boot:
Spring Boot doesn't force the module architecture, but you can have Multi-Module Project in which you have multiple separated modules that are linked in the the main pom.xml (https://www.baeldung.com/spring-boot-multiple-modules).
@Middlewares
Middleware is a function which is called before the route handler.
NestJS:
function CustomMiddleware(req, res, next) {
//CUSTOM middleware.
next();
}
//in the main module
@Module({
imports: [UsersModule],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(CustomMiddleware);
}
}
Equivalent in Spring Boot:
Spring Boot is rich enough that you wouldn't need Middlewares as much as you would in NodeJS, if you worked on authentication in NodeJS you have to set middleware to check on tokens and such, on the other hand, Spring Security for example provides a neat experience through overriding configuration functions and annotations.
But still if you wish to create a middleware in Spring Boot, you can register an Interceptor to do the job.
Strong aspects of NestJS:
Logging support (https://docs.nestjs.com/techniques/logger)
Swagger support (https://docs.nestjs.com/recipes/swagger)
Microservice support (https://docs.nestjs.com/microservices/basics)
GraphQL support (https://docs.nestjs.com/graphql/quick-start)
There're a lot to cover about this amazing Framework, I hope you get a general idea about NestJS and I let you explore the rest through the official documentation.