Files
ostan-complain-api/src/modules/notifications/providers/sms.service.ts
T

62 lines
1.6 KiB
TypeScript

import {
Inject,
Injectable,
InternalServerErrorException,
Logger,
} from '@nestjs/common';
import { SMS_CONFIG } from '../constants';
import type { ISmsConfigs } from 'src/config/sms.config';
import { catchError, firstValueFrom } from 'rxjs';
import { HttpService } from '@nestjs/axios';
import { AxiosError } from 'axios';
import { SmsRequest, SmsSendResponse } from '../interfaces/ISms';
@Injectable()
export class SmsService {
private readonly logger = new Logger(SmsService.name);
constructor(
@Inject(SMS_CONFIG) private smsConfigs: ISmsConfigs,
private readonly httpService: HttpService,
) {}
async sendSms(body: SmsRequest): Promise<SmsSendResponse> {
try {
const { data } = await firstValueFrom(
this.httpService
.post<SmsSendResponse>(
`${this.smsConfigs.API_URL}/send/verify`,
body,
{
headers: {
'X-API-KEY': this.smsConfigs.API_KEY,
},
timeout: 5000,
},
)
.pipe(
catchError((error: AxiosError) => {
this.logger.error(
'Error while calling SMS provider.',
error.stack,
);
throw new InternalServerErrorException(
'Failed to communicate with SMS provider.',
);
}),
),
);
return data;
} catch (error) {
this.logger.error(
'Failed to send SMS.',
error instanceof Error ? error.stack : undefined,
);
throw new InternalServerErrorException('Failed to send SMS.');
}
}
}