Experience in Javascript, Express.js & Node.js writing Rest APIs using Controllers and schemas.
Nest.js is a framework supported by typescript, Where you can implement the OOPS concept, Functional Programming and Function Reactive Programming skills. Ie, If you need to write a scalable and maintainable Node.Js server without breaking it while showing it to friends or clients, Nest.Js is your guy. Nest.js is used to write servers, While we say ‘servers’ it needs Controllers, Routes Schemas etc. Nest.js will force us to write these components in a standard structure. We cannot implement the folder structure from our youtube guru who posted ‘Learn complete Nodejs in 2 hours’.
Let’s say you are writing a few routes to create or update or do any operation in your nest.js server and you would like to perform a common logic like logging every request and response coming into these routes. Writing a method and calling it everywhere in your controller is one method to achieve this, But this will make your code look ugly and hard to maintain. Exactly where an Interceptor comes into play.
$ npm i -g @nestjs/cli
$ nest new project-name
$ npm run start:dev
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common'; import { Observable } from 'rxjs'; import { tap } from 'rxjs/operators'; @Injectable() export class HelloWorldInterceptor implements NestInterceptor { intercept(context: ExecutionContext, next: CallHandler): Observable<any> { // This console.log() will work before entering the contoller console.log("Before entering the contoller") return next.handle().pipe( tap(() => // This console.log() will run after the code executes logic from contoller console.log(`Hello World!`) )); } }
Now let’s tell the contoller to use this interceptor by @UseInterceptor() decorator
Add @UseInterceptors(HelloWorldInterceptor) above @get method of app.contoller.spec.ts
Do not forget to import UseInterceptor from @nestjs/common
Use @UseInterceptor(HelloWorldInterceptor) on top of any controller and your interceptor will be executed every time the contoller is called.
Code is available in github repository : Github
Quick Links
Legal Stuff