Security News
Input Validation Vulnerabilities Dominate MITRE's 2024 CWE Top 25 List
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
@umardraz/ngx-http-retry
Advanced tools
An Angular service that provides HTTP methods (GET
, POST
, PUT
, DELETE
) with built-in retry logic using RxJS's retry
operator.
Install the package via npm:
npm install ngx-http-retry
Import NgxHttpRetryService
into your Angular component or service:
import { NgxHttpRetryService } from 'ngx-http-retry';
@Component({
// ...
})
export class YourComponent {
constructor(private httpRetryService: NgxHttpRetryService) {}
}
The service provides the following methods, which mirror Angular's HttpClient
methods but include retry logic:
get<T>(url: string, options?: any, retries?: number, delayMs?: number): Observable<T>
post<T>(url: string, body: any, options?: any, retries?: number, delayMs?: number): Observable<T>
put<T>(url: string, body: any, options?: any, retries?: number, delayMs?: number): Observable<T>
delete<T>(url: string, options?: any, retries?: number, delayMs?: number): Observable<T>
get
Performs a GET request with retry logic.
Parameters:
url: string
- The endpoint URL.options?: any
- Optional HTTP options.retries?: number
- Number of retry attempts (default: 3
).delayMs?: number
- Delay between retries in milliseconds (default: 1000
).Returns:
Observable<T>
- An observable of the response.Example:
this.httpRetryService.get<User[]>('https://api.example.com/users')
.subscribe(
users => console.log(users),
error => console.error('Request failed', error)
);
post
Performs a POST request with retry logic.
Parameters:
url: string
- The endpoint URL.body: any
- The payload to send.options?: any
- Optional HTTP options.retries?: number
- Number of retry attempts (default: 3
).delayMs?: number
- Delay between retries in milliseconds (default: 1000
).Returns:
Observable<T>
- An observable of the response.Example:
const payload = { name: 'John Doe', email: 'john@example.com' };
this.httpRetryService.post<User>('https://api.example.com/users', payload)
.subscribe(
user => console.log('User created:', user),
error => console.error('Request failed', error)
);
put
Performs a PUT request with retry logic.
Parameters:
url: string
- The endpoint URL.body: any
- The payload to update.options?: any
- Optional HTTP options.retries?: number
- Number of retry attempts (default: 3
).delayMs?: number
- Delay between retries in milliseconds (default: 1000
).Returns:
Observable<T>
- An observable of the response.Example:
const updatedData = { name: 'Jane Doe' };
this.httpRetryService.put<User>('https://api.example.com/users/1', updatedData)
.subscribe(
user => console.log('User updated:', user),
error => console.error('Request failed', error)
);
delete
Performs a DELETE request with retry logic.
Parameters:
url: string
- The endpoint URL.options?: any
- Optional HTTP options.retries?: number
- Number of retry attempts (default: 3
).delayMs?: number
- Delay between retries in milliseconds (default: 1000
).Returns:
Observable<T>
- An observable of the response.Example:
this.httpRetryService.delete<void>('https://api.example.com/users/1')
.subscribe(
() => console.log('User deleted'),
error => console.error('Request failed', error)
);
Customize the number of retries and delay between retries:
this.httpRetryService.get<User[]>('https://api.example.com/users', {}, 5, 2000)
.subscribe(
users => console.log(users),
error => console.error('Request failed after retries', error)
);
5
2000
millisecondsThe retry logic uses RxJS's retry
operator with a custom strategy.
private retryStrategy<T>(retries: number, delayMs: number) {
return retry<T>({
count: retries,
delay: (error: HttpErrorResponse, retryCount: number) => {
if (this.isNonRetryableError(error)) {
throw error;
} else {
console.warn(`Retry attempt #${retryCount}`);
return timer(delayMs);
}
},
});
}
By default, the following HTTP errors are not retried:
4xx
), except for 408 Request Timeout
.private isNonRetryableError(error: HttpErrorResponse): boolean {
return error.status >= 400 && error.status < 500 && error.status !== 408;
}
To implement exponential backoff, modify the retryStrategy
:
private retryStrategy<T>(retries: number, delayMs: number) {
return retry<T>({
count: retries,
delay: (error: HttpErrorResponse, retryCount: number) => {
if (this.isNonRetryableError(error)) {
throw error;
} else {
const backoffDelay = delayMs * Math.pow(2, retryCount - 1);
console.warn(`Retry attempt #${retryCount} after ${backoffDelay}ms`);
return timer(backoffDelay);
}
},
});
}
Customize retry conditions based on specific error codes or responses:
private retryStrategy<T>(retries: number, delayMs: number) {
return retry<T>({
count: retries,
delay: (error: HttpErrorResponse, retryCount: number) => {
if (this.isNonRetryableError(error) || retryCount > retries) {
throw error;
} else if (error.status === 500) {
// Immediate retry for server errors
return timer(0);
} else {
return timer(delayMs);
}
},
});
}
Handle errors where you consume the service:
this.httpRetryService.get<User[]>('https://api.example.com/users')
.subscribe(
users => {
// Successful response
},
error => {
// Error after all retries
console.error('Request failed', error);
}
);
For extensive customization, extend NgxHttpRetryService
:
@Injectable({
providedIn: 'root',
})
export class CustomHttpRetryService extends NgxHttpRetryService {
protected isNonRetryableError(error: HttpErrorResponse): boolean {
// Custom logic (e.g., don't retry on 404)
return error.status === 404;
}
}
Use CustomHttpRetryService
in your components:
constructor(private httpRetryService: CustomHttpRetryService) {}
Yes, it is compatible with Angular Universal.
HttpClient
directly?NgxHttpRetryService
wraps HttpClient
methods and adds configurable retry logic.
Yes, any HTTP request supported by HttpClient
can be used.
Yes, any interceptors configured with HttpClient
are applied.
Contributions are welcome! Please submit issues or pull requests on GitHub.
This project is licensed under the MIT License. See the LICENSE file for details.
FAQs
Angular HTTP client wrapper with configurable retry logic.
The npm package @umardraz/ngx-http-retry receives a total of 5 weekly downloads. As such, @umardraz/ngx-http-retry popularity was classified as not popular.
We found that @umardraz/ngx-http-retry demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.
Research
Security News
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.