redis configuration with bottleneck and shutdown method

pull/1/head
j 2024-03-17 23:25:38 -04:00
parent 76e9014173
commit 39b9d3d9e2
1 changed files with 22 additions and 0 deletions

View File

@ -1,6 +1,10 @@
import axios, { AxiosInstance, AxiosError, AxiosResponse, AxiosRequestConfig } from 'axios';
import axiosRetry from 'axios-retry';
import Bottleneck from 'bottleneck';
import dotenv from 'dotenv';
// Load environment variables from .env file
dotenv.config();
class SessionManager {
private static instance: SessionManager;
@ -8,8 +12,19 @@ class SessionManager {
private limiter: Bottleneck;
private constructor() {
// Initialize the Bottleneck limiter
this.limiter = new Bottleneck({
id: "rDramaAPI-limiter",
datastore: "ioredis",
clearDatastore: false,
clientOptions: {
host: process.env.REDIS_HOST,
port: Number(process.env.REDIS_PORT),
password: process.env.REDIS_PASSWORD || undefined, // Use undefined if no password is set
enableOfflineQueue: true
},
maxConcurrent: 1, // Maximum number of concurrent requests
minTime: 1000 // Minimum time between dispatches of requests in milliseconds
});
@ -38,6 +53,10 @@ class SessionManager {
return SessionManager.instance;
}
public async shutdown(): Promise<void> {
await this.limiter.disconnect();
}
private retryDelayStrategy(retryCount: number, error: AxiosError): number {
const retryAfter = error.response?.headers['retry-after'];
if (retryAfter) {
@ -52,6 +71,7 @@ class SessionManager {
return status === 429 || status >= 500;
}
private wrapAxiosInstance(instance: AxiosInstance): void {
// Wrap the get method
const originalGet = instance.get;
@ -81,6 +101,8 @@ class SessionManager {
public setAuthorizationToken(token: string): void {
this.axiosInstance.defaults.headers.common['Authorization'] = `${token}`;
}
}
export default SessionManager;