Skip to content
This repository has been archived by the owner on Apr 19, 2023. It is now read-only.

Commit

Permalink
✨ Add Twilio module
Browse files Browse the repository at this point in the history
  • Loading branch information
AnandChowdhary committed Nov 1, 2020
1 parent 273c710 commit ec9ec37
Showing 1 changed file with 37 additions and 7 deletions.
44 changes: 37 additions & 7 deletions src/modules/twilio/twilio.service.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,47 @@
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import Twilio from 'twilio';
import twilio from 'twilio';
import PQueue from 'p-queue';
import pRetry from 'p-retry';
import TwilioClient from 'twilio/lib/rest/Twilio';
import { MessageListInstanceCreateOptions } from 'twilio/lib/rest/api/v2010/account/message';

@Injectable()
export class TwilioService {
twilio: Twilio;
twilio: TwilioClient;
logger = new Logger('twilio');
private queue = new PQueue({ concurrency: 1 });

constructor(private configService: ConfigService) {
const twilioApiKey = this.configService.get<string>('sms.twilioApiKey');
if (!twilioApiKey) this.logger.warn('Twilio API key not found');
this.twilio = new Twilio(twilioApiKey ?? '', {
apiVersion: '2020-08-27',
});
const twilioAccountSid = this.configService.get<string>(
'sms.twilioAccountSid',
);
const twilioAuthToken = this.configService.get<string>(
'sms.twilioAuthToken',
);
if (!twilioAccountSid || !twilioAuthToken)
this.logger.warn('Twilio account SID/auth token not found');
this.twilio = twilio(twilioAccountSid ?? '', twilioAuthToken ?? '');
}

send(options: MessageListInstanceCreateOptions) {
this.queue
.add(() =>
pRetry(() => this.sendSms(options), {
retries: 3,
onFailedAttempt: (error) => {
this.logger.error(
`SMS to ${options.to} failed, retrying (${error.retriesLeft} attempts left)`,
error.name,
);
},
}),
)
.then(() => {})
.catch(() => {});
}

private async sendSms(options: MessageListInstanceCreateOptions) {
return this.twilio.messages.create(options);
}
}

0 comments on commit ec9ec37

Please sign in to comment.