@origins-digital/nestjs-concurrency
v1.1.3
Published
Concurrency package
Readme
@origins-digital/nestjs-concurrency
A NestJS module that provides decorators for managing concurrent operations in your NestJS applications.
Installation
npm install @origins-digital/nestjs-concurrencyFeatures
- NestJS decorators for concurrency control
- Automatic lock management
- TTL (Time To Live) configuration for locks
- Context-aware locking
- NestJS integration
Usage
Basic Setup
First, import the ConcurrencyModule in your NestJS application:
import { Module } from '@nestjs/common';
import { ConcurrencyModule } from '@origins-digital/nestjs-concurrency';
@Module({
imports: [ConcurrencyModule],
})
export class AppModule {}Using ConcurrencyHandler Decorator
The @ConcurrencyHandler decorator ensures that only one instance of a method runs at a time:
import { Injectable } from '@nestjs/common';
import { ConcurrencyHandler } from '@origins-digital/nestjs-concurrency';
@Injectable()
export class UserService {
@ConcurrencyHandler({
key: ([id]) => `user:${id}`,
timeoutMs: 30000, // Lock for 30 seconds
excludeContext: false, // Include context in the lock key
})
async updateUser(id: string, data: any) {
// This will only execute if no other instance is running
return this.userRepository.update(id, data);
}
}Decorator Options
The decorator accepts the following options for fine-tuning concurrency behavior:
interface ConcurrencyOptions {
key?: string | ConcurrencyKeyBuilder; // Lock key pattern or function that generates the key
timeoutMs?: number | ConcurrencyTtlBuilder; // Time to live in milliseconds for locks
}Response Format
The decorator returns a promise that resolves to the original method's return value. If the lock cannot be acquired, it will throw a standard JavaScript Error.
Error Handling
The package uses standard JavaScript Error for error handling in the following scenarios:
- When the timeout is reached
- When invalid options are provided
Best Practices
- Always set appropriate timeout values for locks to prevent deadlocks
- Use meaningful key patterns that include unique identifiers
- Monitor lock statistics for performance optimization
- Use the decorator at the service level rather than the controller level
- Use functions for key generation when you need to access method arguments
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under the MIT License - see the LICENSE file for details.
