init
This commit is contained in:
Executable
+150
@@ -0,0 +1,150 @@
|
||||
import { CACHE_MANAGER, Cache } from '@nestjs/cache-manager';
|
||||
import { Inject, Injectable, Logger, OnModuleInit } from '@nestjs/common';
|
||||
|
||||
@Injectable()
|
||||
export class CacheService implements OnModuleInit {
|
||||
private readonly logger = new Logger(CacheService.name);
|
||||
async onModuleInit() {
|
||||
this.logger.log('Pinging Redis to check connection...');
|
||||
try {
|
||||
// 3. Try to set and get a test key
|
||||
await this.cacheManager.set('ping', 'pong', 10); // 10-second TTL
|
||||
const result = await this.cacheManager.get('ping');
|
||||
|
||||
if (result === 'pong') {
|
||||
this.logger.log('✅ Redis connection successful (set/get test passed).');
|
||||
} else {
|
||||
this.logger.error(`❌ Redis connection test failed. Expected 'pong', got '${result}'.`);
|
||||
}
|
||||
|
||||
// 4. Clean up the test key
|
||||
await this.cacheManager.del('ping');
|
||||
} catch (error) {
|
||||
this.logger.error('❌ Failed to connect to Redis during ping test:', error.message);
|
||||
}
|
||||
}
|
||||
|
||||
constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}
|
||||
|
||||
async get<T>(key: string) {
|
||||
return await this.cacheManager.get<T>(key);
|
||||
}
|
||||
|
||||
async set(key: string, value: string, ttl: number = 160) {
|
||||
await this.cacheManager.set(key, value, ttl * 1000);
|
||||
}
|
||||
|
||||
async del(key: string) {
|
||||
await this.cacheManager.del(key);
|
||||
}
|
||||
|
||||
async getTtl(key: string) {
|
||||
return await this.cacheManager.ttl(key);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
// // src/modules/cache/cache.service.ts
|
||||
// import { CACHE_MANAGER, Cache } from '@nestjs/cache-manager';
|
||||
// import { Inject, Injectable, Logger, OnModuleInit } from '@nestjs/common';
|
||||
|
||||
// @Injectable()
|
||||
// export class CacheService implements OnModuleInit {
|
||||
// private readonly logger = new Logger(CacheService.name);
|
||||
|
||||
// constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}
|
||||
|
||||
// /**
|
||||
// * On-init lifecycle hook to test the cache connection.
|
||||
// */
|
||||
// async onModuleInit() {
|
||||
// this.logger.log('Pinging Redis to check connection...');
|
||||
// const testKey = 'ping';
|
||||
// const testValue = 'pong';
|
||||
|
||||
// try {
|
||||
// // 1. Set test key with a 10-second TTL
|
||||
// // Note: We use the wrapper to ensure consistent TTL logic (seconds -> ms)
|
||||
// await this.set(testKey, testValue, 10);
|
||||
|
||||
// // 2. Get test key
|
||||
// const result = await this.get(testKey);
|
||||
|
||||
// if (result === testValue) {
|
||||
// this.logger.log('✅ Redis connection successful (set/get test passed).');
|
||||
// } else {
|
||||
// this.logger.error(
|
||||
// `❌ Redis connection test failed. Expected '${testValue}', got '${result}'.`,
|
||||
// );
|
||||
// }
|
||||
|
||||
// // 3. Clean up the test key
|
||||
// await this.del(testKey);
|
||||
// } catch (error) {
|
||||
// this.logger.error(
|
||||
// '❌ Failed to connect to Redis during ping test:',
|
||||
// error.message,
|
||||
// );
|
||||
// }
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Gets a value from the cache.
|
||||
// * @param key The cache key.
|
||||
// * @returns The cached value or undefined.
|
||||
// */
|
||||
// async get<T>(key: string): Promise<T | undefined> {
|
||||
// try {
|
||||
// return await this.cacheManager.get<T>(key);
|
||||
// } catch (error) {
|
||||
// this.logger.error(`Error getting from cache (key: ${key}):`, error.message);
|
||||
// return undefined; // Fail gracefully
|
||||
// }
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Sets a value in the cache.
|
||||
// * @param key The cache key.
|
||||
// * @param value The value to store (can be any serializable type).
|
||||
// * @param ttlInSeconds The time-to-live in **seconds**.
|
||||
// */
|
||||
// async set(key: string, value: unknown, ttlInSeconds: number = 160): Promise<void> {
|
||||
// try {
|
||||
// // Convert seconds to milliseconds for cache-manager
|
||||
// await this.cacheManager.set(key, value, ttlInSeconds * 1000);
|
||||
// } catch (error) {
|
||||
// this.logger.error(`Error setting cache (key: ${key}):`, error.message);
|
||||
// }
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Deletes a value from the cache.
|
||||
// * @param key The cache key to delete.
|
||||
// */
|
||||
// async del(key: string): Promise<void> {
|
||||
// try {
|
||||
// await this.cacheManager.del(key);
|
||||
// } catch (error)
|
||||
// {
|
||||
// this.logger.error(`Error deleting from cache (key: ${key}):`, error.message);
|
||||
// }
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Gets the remaining TTL for a key in seconds.
|
||||
// * Note: This implementation is specific to redis-store.
|
||||
// * @param key The cache key.
|
||||
// * @returns The remaining TTL in seconds, or -1 (no expiry) / -2 (key doesn't exist).
|
||||
// */
|
||||
// async getTtl(key: string): Promise<number | undefined> {
|
||||
// try {
|
||||
// // The `ttl` method from cache-manager-redis-store returns TTL in seconds
|
||||
// return await this.cacheManager.ttl(key);
|
||||
// } catch (error) {
|
||||
// this.logger.error(`Error getting TTL (key: ${key}):`, error.message);
|
||||
// return undefined;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
@@ -0,0 +1,63 @@
|
||||
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
|
||||
// import { HttpService } from '@nestjs/axios';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
// import { lastValueFrom } from 'rxjs';
|
||||
import axios from 'axios';
|
||||
|
||||
export interface IParameterArray {
|
||||
name: 'otp';
|
||||
value: string;
|
||||
}
|
||||
|
||||
export interface ISmsResponse {
|
||||
status: number;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface ISmsVerifyBody {
|
||||
Parameters: IParameterArray[];
|
||||
Mobile: string;
|
||||
TemplateId: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class SmsService {
|
||||
private readonly baseURL: string;
|
||||
private readonly OTP: string;
|
||||
private readonly apiKey: string;
|
||||
|
||||
constructor(
|
||||
// private readonly httpService: HttpService,
|
||||
private readonly configService: ConfigService,
|
||||
) {
|
||||
this.baseURL = this.configService.getOrThrow<string>('SMS_BASE_URL');
|
||||
this.OTP = this.configService.getOrThrow<string>('SMS_PATTERN_OTP');
|
||||
this.apiKey = this.configService.getOrThrow<string>('SMS_API_KEY');
|
||||
}
|
||||
|
||||
async sendOtp(mobile: string, otp: string) {
|
||||
const smsData: ISmsVerifyBody = {
|
||||
Parameters: [{ name: 'otp', value: otp }],
|
||||
Mobile: mobile,
|
||||
TemplateId: this.OTP,
|
||||
};
|
||||
|
||||
const url = `${this.baseURL}/send/verify`;
|
||||
|
||||
try {
|
||||
const { data } = await axios.post<ISmsResponse>(url, smsData, {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-API-KEY': this.apiKey,
|
||||
},
|
||||
});
|
||||
if (data.status !== 1) {
|
||||
throw new HttpException('The SMS was not sent. Please try again later.', HttpStatus.BAD_GATEWAY);
|
||||
}
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error('SMS sending failed:', JSON.stringify(error));
|
||||
throw new HttpException('The SMS was not sent. Please try again later.', HttpStatus.BAD_GATEWAY);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { CacheService } from './cache.service';
|
||||
import { SmsService } from './sms.service';
|
||||
import { CacheModule } from '@nestjs/cache-manager';
|
||||
import { cacheConfig } from '../../config/cache.config';
|
||||
|
||||
@Module({
|
||||
imports: [CacheModule.registerAsync(cacheConfig())],
|
||||
controllers: [],
|
||||
providers: [CacheService, SmsService],
|
||||
exports: [CacheService, SmsService],
|
||||
})
|
||||
export class UtilsModule {}
|
||||
Reference in New Issue
Block a user