64 lines
1.7 KiB
TypeScript
64 lines
1.7 KiB
TypeScript
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);
|
|
}
|
|
}
|
|
}
|