This repository has been archived by the owner on Apr 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 205
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
273c710
commit ec9ec37
Showing
1 changed file
with
37 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} |