From 8238c8530f7fc3af93c8d003a21dbc63bf9a28c3 Mon Sep 17 00:00:00 2001 From: Jibola Paul Date: Sat, 15 Nov 2025 02:12:53 +0100 Subject: [PATCH 1/2] fix: cleanup code after final tets, include gitignore file for push notification test --- .gitignore | 5 + api-gateway/src/main.ts | 3 - .../src/notification/notification.service.ts | 31 ------ .../src/notification/rabbitmq.service.ts | 1 - email_service/src/email/email.service.ts | 96 ++++--------------- push-service/src/push/push.service.ts | 95 +++++------------- 6 files changed, 49 insertions(+), 182 deletions(-) diff --git a/.gitignore b/.gitignore index 4fb1612..c0c7dfe 100644 --- a/.gitignore +++ b/.gitignore @@ -36,3 +36,8 @@ coverage # Misc *.bak *.tmp + +#push token test +index.html +OneSignalSDK.sw.js +OneSignalSDKWorker.js \ No newline at end of file diff --git a/api-gateway/src/main.ts b/api-gateway/src/main.ts index 44fe570..9ef6e0e 100644 --- a/api-gateway/src/main.ts +++ b/api-gateway/src/main.ts @@ -10,7 +10,6 @@ async function fetchWithRetry(url: string, retries = 5, delay = 2000) { const response = await axios.get(url, { timeout: 5000 }); return response.data; } catch (error) { - console.log(`Attempt ${i + 1} failed for ${url}. Retrying...`); if (i === retries - 1) throw error; await new Promise((resolve) => setTimeout(resolve, delay)); } @@ -48,10 +47,8 @@ async function bootstrap() { for (const service of services) { try { - console.log(`Fetching ${service.name}...`); const doc = await fetchWithRetry(service.url); SwaggerModule.setup(service.path, app, doc); - console.log(`✓ ${service.name} docs available at /${service.path}`); } catch (error) { console.error(`✗ Failed to fetch ${service.name}:`, error.message); } diff --git a/api-gateway/src/notification/notification.service.ts b/api-gateway/src/notification/notification.service.ts index bb84392..e1ec953 100644 --- a/api-gateway/src/notification/notification.service.ts +++ b/api-gateway/src/notification/notification.service.ts @@ -31,17 +31,10 @@ export class NotificationService { user: any, ): Promise> { try { - console.log('=== NOTIFICATION REQUEST START ==='); - console.log('User:', user); - console.log('DTO:', dto); - - // Check for duplicate - console.log('Checking duplicate for request_id:', dto.request_id); const isDuplicate = await this.redisService.checkDuplicate( dto.request_id, ); if (isDuplicate) { - console.log('Duplicate detected!'); const existingNotificationId = await this.redisService.getRequestMapping(dto.request_id); return { @@ -55,15 +48,12 @@ export class NotificationService { // Validate user const userServiceUrl = process.env.USER_SERVICE_URL || 'http://localhost:3001'; - console.log('USER_SERVICE_URL:', userServiceUrl); - console.log('Fetching user:', dto.user_id); let userResponse; try { userResponse = await firstValueFrom( this.httpService.get(`${userServiceUrl}/api/v1/users/${dto.user_id}`), ); - console.log('User fetched successfully:', userResponse.data); } catch (error: any) { console.error('❌ USER SERVICE ERROR:', error.message); console.error('Error details:', error.response?.data || error); @@ -76,10 +66,7 @@ export class NotificationService { } const targetUser = userResponse.data.data; - console.log('Target user:', targetUser); - // Check authorization - console.log('Checking authorization:', user.userId, 'vs', dto.user_id); if (user.userId !== dto.user_id) { console.error('Authorization failed!'); throw new ForbiddenException( @@ -87,13 +74,10 @@ export class NotificationService { ); } - // Check preferences - console.log('Checking user preferences:', targetUser.preferences); if ( dto.notification_type === NotificationType.EMAIL && !targetUser.preferences.email ) { - console.log('User has disabled email notifications'); return { success: false, message: 'User has disabled email notifications', @@ -103,8 +87,6 @@ export class NotificationService { // Get template const templateServiceUrl = process.env.TEMPLATE_SERVICE_URL || 'http://localhost:3004'; - console.log('TEMPLATE_SERVICE_URL:', templateServiceUrl); - console.log('Fetching template:', dto.template_code); let templateResponse; try { @@ -113,7 +95,6 @@ export class NotificationService { `${templateServiceUrl}/api/v1/templates/${dto.template_code}`, ), ); - console.log('Template fetched successfully:', templateResponse.data); } catch (error: any) { console.error('❌ TEMPLATE SERVICE ERROR:', error.message); console.error('Error details:', error.response?.data || error); @@ -127,7 +108,6 @@ export class NotificationService { // Generate notification ID const notificationId = uuidv4(); - console.log('Generated notification_id:', notificationId); // Prepare message const message = { @@ -141,39 +121,28 @@ export class NotificationService { metadata: dto.metadata, timestamp: new Date().toISOString(), }; - console.log('Message prepared:', message); // Route to queue const queue = dto.notification_type === NotificationType.EMAIL ? 'email.queue' : 'push.queue'; - console.log('Publishing to queue:', queue); try { await this.circuitBreaker.execute(async () => { await this.rabbitMQService.publishToQueue(queue, message); }, 'rabbitmq'); - console.log('✅ Message published to queue successfully'); } catch (error: any) { - console.error('❌ RABBITMQ ERROR:', error.message); throw new Error(`Failed to publish to queue: ${error.message}`); } - - // Mark as processed - console.log('Marking request as processed'); await this.redisService.markProcessed(dto.request_id, notificationId); - // Store status - console.log('Storing initial status'); await this.redisService.setStatus(notificationId, { status: NotificationStatus.PENDING, created_at: new Date().toISOString(), notification_type: dto.notification_type, user_id: dto.user_id, }); - - console.log('=== NOTIFICATION REQUEST SUCCESS ==='); return { success: true, message: 'Notification queued successfully', diff --git a/api-gateway/src/notification/rabbitmq.service.ts b/api-gateway/src/notification/rabbitmq.service.ts index b515ab6..d7ccf66 100644 --- a/api-gateway/src/notification/rabbitmq.service.ts +++ b/api-gateway/src/notification/rabbitmq.service.ts @@ -29,7 +29,6 @@ export class RabbitMQService implements OnModuleInit, OnModuleDestroy { }); await this.channelWrapper.waitForConnect(); - console.log('RabbitMQ connected'); } async publishToQueue( diff --git a/email_service/src/email/email.service.ts b/email_service/src/email/email.service.ts index 6afc073..a16602e 100644 --- a/email_service/src/email/email.service.ts +++ b/email_service/src/email/email.service.ts @@ -28,15 +28,13 @@ export class EmailService implements OnModuleInit, OnModuleDestroy { // Initialize SendGrid const apiKey = process.env.SENDGRID_API_KEY; if (!apiKey) { - console.error('❌ SENDGRID_API_KEY environment variable is not set'); + console.error('SENDGRID_API_KEY environment variable is not set'); } else { sgMail.setApiKey(apiKey); - console.log('✅ SendGrid initialized'); } } async onModuleInit() { - console.log('🚀 Email Service initializing...'); // Connect to Redis await this.connectRedis(); @@ -50,19 +48,16 @@ export class EmailService implements OnModuleInit, OnModuleDestroy { private async verifySendGrid() { if (!process.env.SENDGRID_API_KEY) { - console.error('❌ SendGrid API key not configured'); + console.error('SendGrid API key not configured'); console.error('Set SENDGRID_API_KEY environment variable'); return; } if (!process.env.FROM_EMAIL) { - console.error('❌ FROM_EMAIL not configured'); + console.error('FROM_EMAIL not configured'); console.error('Set FROM_EMAIL to your verified sender email'); return; } - - console.log('✅ SendGrid ready to send emails'); - console.log(` From: ${process.env.FROM_EMAIL}`); } private async connectRedis() { @@ -75,11 +70,10 @@ export class EmailService implements OnModuleInit, OnModuleDestroy { port: redisPort, reconnectStrategy: (retries) => { if (retries > 10) { - console.error('❌ Redis max reconnection attempts reached'); + console.error(' Redis max reconnection attempts reached'); return new Error('Max reconnection attempts reached'); } const delay = Math.min(retries * 100, 3000); - console.log(`🔄 Reconnecting to Redis... (attempt ${retries})`); return delay; }, }, @@ -87,13 +81,13 @@ export class EmailService implements OnModuleInit, OnModuleDestroy { }); this.redisClient.on('error', (err) => - console.error('❌ Redis Client Error:', err.message), + console.error('Redis Client Error:', err.message), ); this.redisClient.on('connect', () => - console.log('✅ Email Service: Redis connected'), + console.log('Email Service: Redis connected'), ); this.redisClient.on('reconnecting', () => - console.log('🔄 Redis reconnecting...'), + console.log('Redis reconnecting...'), ); await this.redisClient.connect(); @@ -103,20 +97,17 @@ export class EmailService implements OnModuleInit, OnModuleDestroy { const rabbitMQUrl = process.env.RABBITMQ_URL || 'amqp://admin:admin@localhost:5672'; - console.log('🔌 Connecting to RabbitMQ...'); - console.log(` URL: ${rabbitMQUrl.replace(/\/\/.*:.*@/, '//***:***@')}`); - this.connection = amqp.connect([rabbitMQUrl], { heartbeatIntervalInSeconds: 30, reconnectTimeInSeconds: 5, }); this.connection.on('connect', () => - console.log('✅ RabbitMQ connection established'), + console.log('RabbitMQ connection established'), ); this.connection.on('disconnect', (err) => console.error( - '❌ RabbitMQ disconnected:', + ' RabbitMQ disconnected:', // @ts-expect-error: RabbitMQ error type is unknown and may not contain "message" err?.message || 'Unknown error', ), @@ -124,7 +115,7 @@ export class EmailService implements OnModuleInit, OnModuleDestroy { this.connection.on('connectFailed', (err) => console.error( - '❌ RabbitMQ connection failed:', + ' RabbitMQ connection failed:', // @ts-expect-error: RabbitMQ error type does not strictly match TypeScript's expected shape err?.message || 'Unknown error', ), @@ -133,7 +124,6 @@ export class EmailService implements OnModuleInit, OnModuleDestroy { this.channelWrapper = this.connection.createChannel({ json: true, setup: async (channel: any) => { - console.log('⚙️ Setting up RabbitMQ channel...'); await channel.assertQueue('email.queue', { durable: true, @@ -143,41 +133,23 @@ export class EmailService implements OnModuleInit, OnModuleDestroy { }); await channel.assertQueue('failed.queue', { durable: true }); - console.log('📬 Queues asserted'); - const queueInfo = await channel.checkQueue('email.queue'); - console.log('📊 Queue Status BEFORE consuming:'); - console.log(` Messages in queue: ${queueInfo.messageCount}`); - console.log(` Consumers: ${queueInfo.consumerCount}`); await channel.prefetch(1); - console.log('⚙️ Prefetch set to 1'); const consumerTag = await channel.consume( 'email.queue', async (msg: any) => { if (msg) { - console.log('\n' + '='.repeat(60)); - console.log('🎉 MESSAGE RECEIVED FROM QUEUE!'); - console.log('='.repeat(60)); await this.processEmailMessage(msg, channel); } else { - console.log('⚠️ Received null message'); + console.log('Received null message'); } }, { noAck: false }, ); - console.log(`✅ Consumer started with tag: ${consumerTag.consumerTag}`); - const queueInfoAfter = await channel.checkQueue('email.queue'); - console.log('📊 Queue Status AFTER consumer setup:'); - console.log(` Messages in queue: ${queueInfoAfter.messageCount}`); - console.log(` Consumers: ${queueInfoAfter.consumerCount}`); - - console.log('\n' + '🎧'.repeat(20)); - console.log('👂 EMAIL SERVICE IS NOW LISTENING FOR MESSAGES'); - console.log('🎧'.repeat(20) + '\n'); if (queueInfoAfter.messageCount > 0) { console.log( @@ -188,15 +160,15 @@ export class EmailService implements OnModuleInit, OnModuleDestroy { }); this.channelWrapper.on('error', (err) => { - console.error('❌ Channel error:', err.message); + console.error(' Channel error:', err.message); }); this.channelWrapper.on('close', () => { - console.log('⚠️ Channel closed'); + console.log('Channel closed'); }); await this.channelWrapper.waitForConnect(); - console.log('✅ Email Service connected to RabbitMQ and ready'); + console.log('Email Service connected to RabbitMQ and ready'); } private async processEmailMessage(msg: ConsumeMessage, channel: any) { @@ -204,16 +176,10 @@ export class EmailService implements OnModuleInit, OnModuleDestroy { try { const messageContent = msg.content.toString(); - console.log('📝 Raw message content:', messageContent); const message = JSON.parse(messageContent); correlationId = message.notification_id; - console.log(`\n=== PROCESSING EMAIL ===`); - console.log(`Notification ID: ${correlationId}`); - console.log(`Recipient: ${message.user_email}`); - console.log(`Subject Template: ${message.template?.subject || 'N/A'}`); - await this.updateStatus(correlationId, NotificationStatus.PROCESSING); const titleTemplate = Handlebars.compile( @@ -224,8 +190,6 @@ export class EmailService implements OnModuleInit, OnModuleDestroy { const subject = titleTemplate(message.variables || {}); const html = bodyTemplate(message.variables || {}); - console.log(`📧 Sending email with subject: "${subject}"`); - // Send email via SendGrid const emailMsg = { to: message.user_email, @@ -236,10 +200,6 @@ export class EmailService implements OnModuleInit, OnModuleDestroy { const response = await sgMail.send(emailMsg); - console.log(`✅ Email sent successfully via SendGrid!`); - console.log(` Status Code: ${response[0].statusCode}`); - console.log(` Message ID: ${response[0].headers['x-message-id']}`); - await this.updateStatus( correlationId, NotificationStatus.DELIVERED, @@ -254,11 +214,8 @@ export class EmailService implements OnModuleInit, OnModuleDestroy { channel.ack(msg); this.retryAttempts.delete(correlationId); - - console.log(`✅ Message acknowledged and removed from queue`); - console.log(`=== EMAIL PROCESSING COMPLETE ===\n`); } catch (error) { - console.error(`\n❌ FAILED TO SEND EMAIL`); + console.error(`\n FAILED TO SEND EMAIL`); console.error(` Notification ID: ${correlationId}`); console.error(` Error: ${error.message}`); @@ -274,8 +231,6 @@ export class EmailService implements OnModuleInit, OnModuleDestroy { this.retryAttempts.set(correlationId, attempts + 1); const delay = Math.pow(2, attempts) * 1000; - console.log(`🔄 Will retry in ${delay}ms (attempt ${attempts + 1}/3)`); - await this.updateStatus( correlationId, NotificationStatus.RETRYING, @@ -283,11 +238,9 @@ export class EmailService implements OnModuleInit, OnModuleDestroy { ); setTimeout(() => { - console.log(`🔄 Requeuing message for retry...`); channel.nack(msg, false, true); }, delay); } else { - console.log(`☠️ Max retries exceeded. Moving to dead letter queue.`); await channel.sendToQueue('failed.queue', msg.content, { persistent: true, @@ -306,7 +259,6 @@ export class EmailService implements OnModuleInit, OnModuleDestroy { channel.ack(msg); this.retryAttempts.delete(correlationId); - console.log(`=== EMAIL PROCESSING FAILED ===\n`); } } } @@ -352,8 +304,6 @@ export class EmailService implements OnModuleInit, OnModuleDestroy { JSON.stringify(updatedStatus), ); - console.log(`📊 Redis status updated: ${notificationId} -> ${status}`); - const apiGatewayUrl = process.env.API_GATEWAY_URL || 'http://localhost:3000'; @@ -372,39 +322,35 @@ export class EmailService implements OnModuleInit, OnModuleDestroy { }, ), ); - console.log( - `📡 API Gateway status updated: ${notificationId} -> ${status}`, - ); } catch (apiError) { console.warn( - `⚠️ Failed to update status via API Gateway (non-critical): ${apiError.message}`, + `Failed to update status via API Gateway (non-critical): ${apiError.message}`, ); } } catch (err) { - console.error(`❌ Failed to update status: ${err.message}`); + console.error(` Failed to update status: ${err.message}`); } } async onModuleDestroy() { - console.log('🛑 Shutting down Email Service...'); try { if (this.channelWrapper) { await this.channelWrapper.close(); - console.log('✅ Channel closed'); + console.log('Channel closed'); } if (this.connection) { await this.connection.close(); - console.log('✅ RabbitMQ connection closed'); + console.log('RabbitMQ connection closed'); } if (this.redisClient) { await this.redisClient.quit(); - console.log('✅ Redis connection closed'); + console.log('Redis connection closed'); } } catch (error) { - console.error('❌ Error during shutdown:', error.message); + console.error(' Error during shutdown:', error.message); } console.log('👋 Email Service shut down complete'); diff --git a/push-service/src/push/push.service.ts b/push-service/src/push/push.service.ts index 0bcf2cb..36efd03 100644 --- a/push-service/src/push/push.service.ts +++ b/push-service/src/push/push.service.ts @@ -35,7 +35,6 @@ export class PushService implements OnModuleInit, OnModuleDestroy { constructor(private readonly httpService: HttpService) {} async onModuleInit() { - console.log('🚀 Push Service initializing...'); await this.connectRedis(); await this.connectRabbitMQ(); await this.verifyOneSignal(); @@ -43,13 +42,10 @@ export class PushService implements OnModuleInit, OnModuleDestroy { private async verifyOneSignal() { if (!process.env.ONESIGNAL_APP_ID || !process.env.ONESIGNAL_API_KEY) { - console.error('❌ OneSignal not configured'); + console.error('OneSignal not configured'); console.error('Set ONESIGNAL_APP_ID and ONESIGNAL_API_KEY environment variables'); return; } - - console.log('✅ OneSignal ready to send push notifications'); - console.log(` App ID: ${process.env.ONESIGNAL_APP_ID.substring(0, 8)}...`); } private async connectRedis() { @@ -62,11 +58,10 @@ export class PushService implements OnModuleInit, OnModuleDestroy { port: redisPort, reconnectStrategy: (retries) => { if (retries > 10) { - console.error('❌ Redis max reconnection attempts reached'); + console.error('Redis max reconnection attempts reached'); return new Error('Max reconnection attempts reached'); } const delay = Math.min(retries * 100, 3000); - console.log(`🔄 Reconnecting to Redis... (attempt ${retries})`); return delay; }, }, @@ -74,13 +69,13 @@ export class PushService implements OnModuleInit, OnModuleDestroy { }); this.redisClient.on('error', (err) => - console.error('❌ Redis Client Error:', err.message), + console.error('Redis Client Error:', err.message), ); this.redisClient.on('connect', () => - console.log('✅ Push Service: Redis connected'), + console.log('Push Service: Redis connected'), ); this.redisClient.on('reconnecting', () => - console.log('🔄 Redis reconnecting...'), + console.log('Redis reconnecting...'), ); await this.redisClient.connect(); @@ -90,20 +85,17 @@ export class PushService implements OnModuleInit, OnModuleDestroy { const rabbitMQUrl = process.env.RABBITMQ_URL || 'amqp://admin:admin@localhost:5672'; - console.log('🔌 Connecting to RabbitMQ...'); - console.log(` URL: ${rabbitMQUrl.replace(/\/\/.*:.*@/, '//***:***@')}`); - this.connection = amqp.connect([rabbitMQUrl], { heartbeatIntervalInSeconds: 30, reconnectTimeInSeconds: 5, }); this.connection.on('connect', () => - console.log('✅ RabbitMQ connection established'), + console.log('RabbitMQ connection established'), ); this.connection.on('disconnect', (err) => console.error( - '❌ RabbitMQ disconnected:', + 'RabbitMQ disconnected:', // @ts-expect-error: RabbitMQ error type err?.message || 'Unknown error', ), @@ -112,7 +104,6 @@ export class PushService implements OnModuleInit, OnModuleDestroy { this.channelWrapper = this.connection.createChannel({ json: true, setup: async (channel: any) => { - console.log('⚙️ Setting up RabbitMQ channel...'); await channel.assertQueue('push.queue', { durable: true, @@ -122,41 +113,24 @@ export class PushService implements OnModuleInit, OnModuleDestroy { }); await channel.assertQueue('failed.queue', { durable: true }); - console.log('📬 Queues asserted'); const queueInfo = await channel.checkQueue('push.queue'); - console.log('📊 Queue Status BEFORE consuming:'); - console.log(` Messages in queue: ${queueInfo.messageCount}`); - console.log(` Consumers: ${queueInfo.consumerCount}`); await channel.prefetch(1); - console.log('⚙️ Prefetch set to 1'); const consumerTag = await channel.consume( 'push.queue', async (msg: any) => { if (msg) { - console.log('\n' + '='.repeat(60)); - console.log('🎉 MESSAGE RECEIVED FROM QUEUE!'); - console.log('='.repeat(60)); await this.processPushMessage(msg, channel); } else { - console.log('⚠️ Received null message'); + console.log('Received null message'); } }, { noAck: false }, // IMPORTANT: Must be false for manual ack ); - console.log(`✅ Consumer started with tag: ${consumerTag.consumerTag}`); - const queueInfoAfter = await channel.checkQueue('push.queue'); - console.log('📊 Queue Status AFTER consumer setup:'); - console.log(` Messages in queue: ${queueInfoAfter.messageCount}`); - console.log(` Consumers: ${queueInfoAfter.consumerCount}`); - - console.log('\n' + '🎧'.repeat(20)); - console.log('👂 PUSH SERVICE IS NOW LISTENING FOR MESSAGES'); - console.log('🎧'.repeat(20) + '\n'); if (queueInfoAfter.messageCount > 0) { console.log( @@ -167,15 +141,15 @@ export class PushService implements OnModuleInit, OnModuleDestroy { }); this.channelWrapper.on('error', (err) => { - console.error('❌ Channel error:', err.message); + console.error('Channel error:', err.message); }); this.channelWrapper.on('close', () => { - console.log('⚠️ Channel closed'); + console.log('Channel closed'); }); await this.channelWrapper.waitForConnect(); - console.log('✅ Push Service connected to RabbitMQ and ready'); + console.log('Push Service connected to RabbitMQ and ready'); } private async processPushMessage(msg: ConsumeMessage, channel: any) { @@ -183,18 +157,12 @@ export class PushService implements OnModuleInit, OnModuleDestroy { try { const messageContent = msg.content.toString(); - console.log('📝 Raw message content:', messageContent); const message = JSON.parse(messageContent); correlationId = message.notification_id; - console.log(`\n=== PROCESSING PUSH NOTIFICATION ===`); - console.log(`Notification ID: ${correlationId}`); - console.log(`User ID: ${message.user_id}`); - console.log(`Push Token: ${message.user_push_token ? 'Present' : 'Missing'}`); - if (!message.user_push_token) { - console.error('❌ No push token available for user'); + console.error('No push token available for user'); await this.updateStatus( correlationId, NotificationStatus.FAILED, @@ -214,8 +182,6 @@ export class PushService implements OnModuleInit, OnModuleDestroy { const title = titleTemplate(message.variables || {}); const body = bodyTemplate(message.variables || {}); - console.log(`📱 Sending push notification: "${title}"`); - const response = await this.sendPushNotification({ token: message.user_push_token, title, @@ -223,9 +189,6 @@ export class PushService implements OnModuleInit, OnModuleDestroy { data: message.metadata, }); - console.log(`✅ Push notification sent successfully!`); - console.log(` OneSignal ID: ${response.messageId}`); - await this.updateStatus( correlationId, NotificationStatus.DELIVERED, @@ -241,10 +204,8 @@ export class PushService implements OnModuleInit, OnModuleDestroy { channel.ack(msg); this.retryAttempts.delete(correlationId); - console.log(`✅ Message acknowledged and removed from queue`); - console.log(`=== PUSH NOTIFICATION COMPLETE ===\n`); } catch (error: any) { - console.error(`\n❌ FAILED TO SEND PUSH NOTIFICATION`); + console.error(`\nFAILED TO SEND PUSH NOTIFICATION`); console.error(` Notification ID: ${correlationId}`); console.error(` Error: ${error.message}`); @@ -254,8 +215,6 @@ export class PushService implements OnModuleInit, OnModuleDestroy { this.retryAttempts.set(correlationId, attempts + 1); const delay = Math.pow(2, attempts) * 1000; - console.log(`🔄 Will retry in ${delay}ms (attempt ${attempts + 1}/3)`); - await this.updateStatus( correlationId, NotificationStatus.RETRYING, @@ -263,11 +222,9 @@ export class PushService implements OnModuleInit, OnModuleDestroy { ); setTimeout(() => { - console.log(`🔄 Requeuing message for retry...`); channel.nack(msg, false, true); }, delay); } else { - console.log(`☠️ Max retries exceeded. Moving to dead letter queue.`); await channel.sendToQueue('failed.queue', msg.content, { persistent: true, @@ -286,7 +243,6 @@ export class PushService implements OnModuleInit, OnModuleDestroy { channel.ack(msg); this.retryAttempts.delete(correlationId); - console.log(`=== PUSH NOTIFICATION FAILED ===\n`); } } } @@ -296,7 +252,7 @@ export class PushService implements OnModuleInit, OnModuleDestroy { const oneSignalApiKey = process.env.ONESIGNAL_API_KEY; if (!oneSignalAppId || !oneSignalApiKey) { - console.warn('⚠️ OneSignal not configured - simulating push send'); + console.warn('OneSignal not configured - simulating push send'); return { messageId: `simulated_${Date.now()}` }; } @@ -323,7 +279,7 @@ export class PushService implements OnModuleInit, OnModuleDestroy { return { messageId: response.data.id }; } catch (error: any) { - console.error('❌ OneSignal API Error:', error.response?.data || error.message); + console.error('OneSignal API Error:', error.response?.data || error.message); throw new Error(`OneSignal send failed: ${error.message}`); } } @@ -369,8 +325,6 @@ export class PushService implements OnModuleInit, OnModuleDestroy { JSON.stringify(updatedStatus), ); - console.log(`📊 Redis status updated: ${notificationId} -> ${status}`); - const apiGatewayUrl = process.env.API_GATEWAY_URL || 'http://localhost:3000'; @@ -389,41 +343,38 @@ export class PushService implements OnModuleInit, OnModuleDestroy { }, ), ); - console.log( - `📡 API Gateway status updated: ${notificationId} -> ${status}`, - ); } catch (apiError: any) { console.warn( - `⚠️ Failed to update status via API Gateway (non-critical): ${apiError.message}`, + `Failed to update status via API Gateway (non-critical): ${apiError.message}`, ); } } catch (err: any) { - console.error(`❌ Failed to update status: ${err.message}`); + console.error(`Failed to update status: ${err.message}`); } } async onModuleDestroy() { - console.log('🛑 Shutting down Push Service...'); + console.log('Shutting down Push Service...'); try { if (this.channelWrapper) { await this.channelWrapper.close(); - console.log('✅ Channel closed'); + console.log('Channel closed'); } if (this.connection) { await this.connection.close(); - console.log('✅ RabbitMQ connection closed'); + console.log('RabbitMQ connection closed'); } if (this.redisClient) { await this.redisClient.quit(); - console.log('✅ Redis connection closed'); + console.log('Redis connection closed'); } } catch (error: any) { - console.error('❌ Error during shutdown:', error.message); + console.error('Error during shutdown:', error.message); } - console.log('👋 Push Service shut down complete'); + console.log('Push Service shut down complete'); } } \ No newline at end of file From 04941967a0c88d8d4ee978dfe1e5ace06af570f7 Mon Sep 17 00:00:00 2001 From: Jibola Paul Date: Sat, 15 Nov 2025 02:21:14 +0100 Subject: [PATCH 2/2] fix: lint errors --- email_service/src/email/email.module.ts | 2 +- email_service/src/email/email.service.ts | 18 ----------- email_service/src/health/health.controller.ts | 2 +- email_service/src/health/health.module.ts | 2 +- push-service/src/app.module.ts | 2 +- push-service/src/health/health.controller.ts | 2 +- push-service/src/health/health.module.ts | 2 +- push-service/src/push/push.service.ts | 32 +++++-------------- 8 files changed, 14 insertions(+), 48 deletions(-) diff --git a/email_service/src/email/email.module.ts b/email_service/src/email/email.module.ts index feb25cb..f4aebb3 100644 --- a/email_service/src/email/email.module.ts +++ b/email_service/src/email/email.module.ts @@ -6,4 +6,4 @@ import { EmailService } from './email.service'; imports: [HttpModule], providers: [EmailService], }) -export class EmailModule {} \ No newline at end of file +export class EmailModule {} diff --git a/email_service/src/email/email.service.ts b/email_service/src/email/email.service.ts index a16602e..1c5eb10 100644 --- a/email_service/src/email/email.service.ts +++ b/email_service/src/email/email.service.ts @@ -35,7 +35,6 @@ export class EmailService implements OnModuleInit, OnModuleDestroy { } async onModuleInit() { - // Connect to Redis await this.connectRedis(); @@ -124,7 +123,6 @@ export class EmailService implements OnModuleInit, OnModuleDestroy { this.channelWrapper = this.connection.createChannel({ json: true, setup: async (channel: any) => { - await channel.assertQueue('email.queue', { durable: true, arguments: { @@ -133,22 +131,8 @@ export class EmailService implements OnModuleInit, OnModuleDestroy { }); await channel.assertQueue('failed.queue', { durable: true }); - const queueInfo = await channel.checkQueue('email.queue'); - await channel.prefetch(1); - const consumerTag = await channel.consume( - 'email.queue', - async (msg: any) => { - if (msg) { - await this.processEmailMessage(msg, channel); - } else { - console.log('Received null message'); - } - }, - { noAck: false }, - ); - const queueInfoAfter = await channel.checkQueue('email.queue'); if (queueInfoAfter.messageCount > 0) { @@ -241,7 +225,6 @@ export class EmailService implements OnModuleInit, OnModuleDestroy { channel.nack(msg, false, true); }, delay); } else { - await channel.sendToQueue('failed.queue', msg.content, { persistent: true, headers: { @@ -333,7 +316,6 @@ export class EmailService implements OnModuleInit, OnModuleDestroy { } async onModuleDestroy() { - try { if (this.channelWrapper) { await this.channelWrapper.close(); diff --git a/email_service/src/health/health.controller.ts b/email_service/src/health/health.controller.ts index 2f20241..85c015d 100644 --- a/email_service/src/health/health.controller.ts +++ b/email_service/src/health/health.controller.ts @@ -13,4 +13,4 @@ export class HealthController { timestamp: new Date().toISOString(), }; } -} \ No newline at end of file +} diff --git a/email_service/src/health/health.module.ts b/email_service/src/health/health.module.ts index e161404..7476abe 100644 --- a/email_service/src/health/health.module.ts +++ b/email_service/src/health/health.module.ts @@ -4,4 +4,4 @@ import { HealthController } from './health.controller'; @Module({ controllers: [HealthController], }) -export class HealthModule {} \ No newline at end of file +export class HealthModule {} diff --git a/push-service/src/app.module.ts b/push-service/src/app.module.ts index 0982f9c..28d81cf 100644 --- a/push-service/src/app.module.ts +++ b/push-service/src/app.module.ts @@ -6,4 +6,4 @@ import { HttpModule } from '@nestjs/axios'; @Module({ imports: [HttpModule, PushModule, HealthModule], }) -export class AppModule {} \ No newline at end of file +export class AppModule {} diff --git a/push-service/src/health/health.controller.ts b/push-service/src/health/health.controller.ts index afe18aa..f8a2d68 100644 --- a/push-service/src/health/health.controller.ts +++ b/push-service/src/health/health.controller.ts @@ -13,4 +13,4 @@ export class HealthController { timestamp: new Date().toISOString(), }; } -} \ No newline at end of file +} diff --git a/push-service/src/health/health.module.ts b/push-service/src/health/health.module.ts index e161404..7476abe 100644 --- a/push-service/src/health/health.module.ts +++ b/push-service/src/health/health.module.ts @@ -4,4 +4,4 @@ import { HealthController } from './health.controller'; @Module({ controllers: [HealthController], }) -export class HealthModule {} \ No newline at end of file +export class HealthModule {} diff --git a/push-service/src/push/push.service.ts b/push-service/src/push/push.service.ts index 36efd03..5afe6ba 100644 --- a/push-service/src/push/push.service.ts +++ b/push-service/src/push/push.service.ts @@ -43,7 +43,9 @@ export class PushService implements OnModuleInit, OnModuleDestroy { private async verifyOneSignal() { if (!process.env.ONESIGNAL_APP_ID || !process.env.ONESIGNAL_API_KEY) { console.error('OneSignal not configured'); - console.error('Set ONESIGNAL_APP_ID and ONESIGNAL_API_KEY environment variables'); + console.error( + 'Set ONESIGNAL_APP_ID and ONESIGNAL_API_KEY environment variables', + ); return; } } @@ -104,7 +106,6 @@ export class PushService implements OnModuleInit, OnModuleDestroy { this.channelWrapper = this.connection.createChannel({ json: true, setup: async (channel: any) => { - await channel.assertQueue('push.queue', { durable: true, arguments: { @@ -113,23 +114,8 @@ export class PushService implements OnModuleInit, OnModuleDestroy { }); await channel.assertQueue('failed.queue', { durable: true }); - - const queueInfo = await channel.checkQueue('push.queue'); - await channel.prefetch(1); - const consumerTag = await channel.consume( - 'push.queue', - async (msg: any) => { - if (msg) { - await this.processPushMessage(msg, channel); - } else { - console.log('Received null message'); - } - }, - { noAck: false }, // IMPORTANT: Must be false for manual ack - ); - const queueInfoAfter = await channel.checkQueue('push.queue'); if (queueInfoAfter.messageCount > 0) { @@ -203,7 +189,6 @@ export class PushService implements OnModuleInit, OnModuleDestroy { channel.ack(msg); this.retryAttempts.delete(correlationId); - } catch (error: any) { console.error(`\nFAILED TO SEND PUSH NOTIFICATION`); console.error(` Notification ID: ${correlationId}`); @@ -225,7 +210,6 @@ export class PushService implements OnModuleInit, OnModuleDestroy { channel.nack(msg, false, true); }, delay); } else { - await channel.sendToQueue('failed.queue', msg.content, { persistent: true, headers: { @@ -279,7 +263,10 @@ export class PushService implements OnModuleInit, OnModuleDestroy { return { messageId: response.data.id }; } catch (error: any) { - console.error('OneSignal API Error:', error.response?.data || error.message); + console.error( + 'OneSignal API Error:', + error.response?.data || error.message, + ); throw new Error(`OneSignal send failed: ${error.message}`); } } @@ -354,8 +341,6 @@ export class PushService implements OnModuleInit, OnModuleDestroy { } async onModuleDestroy() { - console.log('Shutting down Push Service...'); - try { if (this.channelWrapper) { await this.channelWrapper.close(); @@ -374,7 +359,6 @@ export class PushService implements OnModuleInit, OnModuleDestroy { } catch (error: any) { console.error('Error during shutdown:', error.message); } - console.log('Push Service shut down complete'); } -} \ No newline at end of file +}