Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

🛡️ A module for improving the reliability and fault-tolerance of your NestJS applications

License

NotificationsYou must be signed in to change notification settings

SocketSomeone/nestjs-resilience

Repository files navigation

Nest Logo

A module for improving the reliability and fault-tolerance of yourNestJS applications

NPM VersionNPM LicenseNPM DownloadsLast commit

About

NestJS Resilience is an open-source library that provides a set of reliable patterns for building resilient applications on top of NestJS.The library includes several key features, including retry, circuit breaker, and timeout patterns, which help to ensure that yourapplication can handle failures and recover quickly from them.

With NestJS Resilience, you can easily configure these patterns for your application, allowing you to improve the reliability andfault-tolerance of your services. Whether you're building a high-traffic web application or a distributed system, NestJS Resilience providesthe tools you need to build robust, failure-resistant services that can withstand even the most challenging environments.

Features

  • Circuit Breaker - Automatically fail fast when a service is unavailable
  • Retry - Automatically retry failed requests
  • Timeout - Automatically fail fast when a service is taking too long to respond
  • Bulkhead - Limit the number of concurrent requests to a service
  • Fallback - Provide a fallback response when a service is unavailable
  • Rate Limiting - Limit the number of requests to a service
  • De duplicate - Prevent duplicate requests from being processed

Installation

$ npm install nestjs-resilience$ yarn add nestjs-resilience$ pnpm add nestjs-resilience

Usage

Import the module

import{Module}from'@nestjs/common';import{ResilienceModule}from'nestjs-resilience';@Module({imports:[ResilienceModule.forRoot()]})exportclassAppModule{}

Usestore field to configure cache (e.x.store: new RedisStore({ host: 'localhost', port: 6379 })).We usememory fromcache-manager store by default.

Ways to use

You can use it in three ways:

1. UseResilienceCommand

You can create a command by extending theResilienceCommand class. You can also use theResilienceFactory to create a command with a setof policies.

import{Injectable}from'@nestjs/common';import{ResilienceCommand,ResilienceFactory}from'nestjs-resilience';import{UsersService}from'./user.service';import{User,NullUserObject}from'./user.entity';@Injectable()exportclassGetUserByIdCommandextendsResilienceCommand{constructor(privatereadonlyfactory:ResilienceFactory,privatereadonlyuserService:UsersService){super([// You can use the injected factory to create a strategyfactory.createTimeout(1000),// Or you can create a strategy directlyResilienceFactory.createFallback((id)=>newNullUserObject(id))// You can also use mannually created strategies// new TimeoutStrategy(1000),]);}asyncrun(id:number):User{returnthis.usersService.getUser(id);}}

This way supports DI, just what you need add@Injectable() decorator to your command and to providers of your module. Inject yourcommand in the constructor or useresilienceService.getCommand(GetUserByIdCommand).

FAQ:

  • Can I use@Inject() decorator? Yes, you can. But you need to add@Injectable() decorator to your command.
  • Can I use w/o DI? Yes, you can. Just create a command withnew operator.

2. Use the@UseResilience() decorator

You can use@UseResilience() decorator to wrap yourservice methods.

import{Injectable}from'@nestjs/common';import{TimeoutStrategy}from"./timeout.strategy";import{NullUserObject,User}from'./user.entity';@Injectable()exportclassUsersService{    @UseResilience(newTimeoutStrategy(1000),ResilienceFactory.createFallback((id)=>newNullUserObject(id)))asyncgetUser(id:number):User{returnthis.httpService.get(`https://example.com/users/${id}`).toPromise();}}

Not the best way to use in controller methods.@UseResilience rewrite your method.

3. Interceptors

You also can wrap your controller methods withResilienceInterceptor and use all the features of the library.

import{Controller,Get,UseInterceptors}from'@nestjs/common';import{ResilienceInterceptor}from'nestjs-resilience';import{UsersService}from'./users.service';@Controller('users')exportclassUsersController{constructor(privatereadonlyusersService:UsersService){}    @Get()    @UseInterceptors(ResilienceInterceptor(newTimeoutStrategy(1000),ResilienceFactory.createFallback(()=>[])))asyncgetUsers():User[]{returnthis.usersService.getUsers();}}

Observables

We also supportObservable as a return type. You can use it with@UseResilienceObservable() decorator orResilienceCommandObservable.

import{Injectable}from'@nestjs/common';import{TimeoutStrategy}from"./timeout.strategy";import{NullUserObject,User}from'./user.entity';import{Observable,of}from'rxjs';@Injectable()exportclassUsersService{    @UseResilienceObservable(newTimeoutStrategy(1000),ResilienceFactory.createFallback((id)=>newNullUserObject(id)))getUser(id:number):Observable<User>{returnof(newUser(id,'John Doe'));}}

Order of execution

Strategies processing in order which you pass them to theResilienceCommand orResilienceInterceptor.

What it means? Let's take a look at the example:

Timeout before Retry:

  • If the command is executed successfully, the result will be returned.
  • If the command is executed with an error or timed out, the command will be retried.
  • If the command is executed with an error or timed out and the number of retries is exceeded, the error will be thrown.

Retry after Timeout:

  • If the command is executed successfully, the result will be returned.
  • If the command is executed with an error, the command will be retried.
  • If the command is executed with an error and the number of retries is exceeded, the error will be thrown.
  • If the command is executed with an error and the number of retries is exceeded or timed out, the error will be thrown.

Strategies

StrategyDescription
TimeoutStrategyAutomatically fail fast when a service is taking too long to respond
RetryStrategyAutomatically retry failed requests
CircuitBreakerStrategyAutomatically fail fast when a service is unavailable
BulkheadStrategyLimit the number of concurrent requests to a service
FallbackStrategyProvide a fallback response when a service is unavailable
ThrottleStrategyLimit the number of requests to a service
HealthCheckStrategyCheck the health of a service
CacheStrategyCache the result of a service call
DeduplicateStrategyPrevent duplicate requests from being processed

Stay in touch

License

MIT ©Alexey Filippov

About

🛡️ A module for improving the reliability and fault-tolerance of your NestJS applications

Topics

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Sponsor this project

    Packages

    No packages published

    Contributors4

    •  
    •  
    •  
    •  

    [8]ページ先頭

    ©2009-2025 Movatter.jp