Interceptors in Nest.js: A Practical Example

Interceptors in Nest.js: A Practical Example

One often overlooked yet powerful tool in Nest.js is interceptors, they allow us to intercept incoming requests and outgoing responses and inject custom logic at various points in the request/response lifecycle.

Let's imagine a ticketing system, where tickets created via an API endpoint. Here's a simplified version of our Nest.js controller handling this functionality:

Now, suppose we want to track the performance of this endpoint and report any requests taking longer than 2 seconds to process, or failed requests.

Naive Approach: Measuring Request Time in Controllers

We're manually measuring the time taken for request processing within the controller method itself. While this approach may seem straightforward, it comes with several drawbacks:

  1. Code Duplication: If you need to measure multiple endpoints, you'd need to add this logic to each one, making your codebase harder to maintain.
  2. Violation of Single Responsibility Principle (SRP): Processing logic is mixed with timing measurement, the controller method is taking on multiple responsibilities. This violates the SRP and makes the code harder to understand and maintain.
  3. Limited Flexibility: It's challenging to modify or extend the logging behavior without modifying the controller itself. If you wanted to add additional metrics or customize the logging behavior, you'd need to update every controller method.

A Cleaner Solution: Implementing Metrics Interceptor for Enhanced Monitoring

EZ??

Let's apply the interceptor globally:

By applying the MetricsInterceptor globally, we can effortlessly monitor the performance of our endpoints. Any requests taking longer than 2 seconds to process will be logged, allowing us to identify potential bottlenecks and optimize our code accordingly.

Now let's clean up the controller, simulate a long running request, and test our MetricsInterceptor:

We use setTimeout to exceed our 2000ms threshold

Now when we hit our /ticket endpoint, the following will be logged:

??

Interceptors, as demonstrated in this example, provide a clean and efficient way to inject cross-cutting concerns into our Nest.js applications. Whether it's logging, authentication, error handling, or performance monitoring, interceptors empower us to enhance the functionality and reliability of our applications without cluttering our core business logic.

Don't overlook the power of interceptors in your Nest.js applications. Embrace them as a valuable tool in your toolkit, and unlock new possibilities for improving the performance and maintainability of your codebase.


More on Nest.js:

NestJS - DTO Validation: Unleashing the Power of Custom Decorators


Mobsesian David

Senior Backend Developer. ASP.NET Core

1 年

Nice example of code optimization.

回复

要查看或添加评论,请登录

Sergei Kashkin的更多文章

社区洞察

其他会员也浏览了