Reputation: 2298
I'd like to create an @IgnoreDev
decorator that overrides a method return on a NestJS controller when it detects that we're running code in a dev environment.
For example:
@Controller()
class SomeController {
@IgnoreDev
async processMessage(...) {
return 'processed';
}
}
The @IgnoreDev
annotation would detect that process.env.NODE_ENV === 'development'
and return ignored
instead of processed
;
Upvotes: 0
Views: 1233
Reputation: 457
I would agree with Mical Levi. You can use Interceptors for overriding the response from the controller.
Create a new file with the name response.override.interceptor.ts Place the following code :
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from "@nestjs/common";
import { Observable } from "rxjs";
import { tap } from "rxjs/operators";
@Injectable()
export class OverrideResponseInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(
map((data) => {
if (process.env.NODE_ENV === "development") return "ignored ";
else return "processed";
})
);
}
}
After creating the interceptor you just have to place the @UseInterceptors() decorator (imported from nestjs/common package ) over the controller and pass the recently created interceptor inside the decorator.
@Controller()
class SomeController {
@UseInterceptors(OverrideResponseInterceptor)
async processMessage(...) {
return 'processed';
}
}
And that's it You can also watch youtube video on interceptors where I gave the detailed Explanation of Interceptors https://youtu.be/v5zvWQagcO0
Extra Tip
Instead of using env variables as process.env.NODE_ENV I would recommend you to use @nestjs/config package which gives extra abstraction over the env variables. If you are interested you can watch the following video https://youtu.be/7OJE4wwZ0R0 You can also read the documentation on env variables at https://docs.nestjs.com/techniques/configuration
Upvotes: 2