chore: sms service with configs

This commit is contained in:
matin jamshidi
2025-01-19 14:46:16 +03:30
parent b899b8df6f
commit a934e5b55e
8 changed files with 132 additions and 4 deletions
+30
View File
@@ -0,0 +1,30 @@
import { ConfigService } from "@nestjs/config";
export function SmsConfigs() {
return {
inject: [ConfigService],
useFactory(configService: ConfigService) {
return {
URL: configService.getOrThrow<string>("URL"),
API_KEY: configService.getOrThrow<string>("API_KEY"),
SECRET_KEY: configService.getOrThrow<string>("SECRET_KEY"),
SMS_PATTERN_OTP: configService.getOrThrow<string>("SMS_PATTERN_OTP"),
SMS_SECRET_BODY: {
UserApiKey: configService.getOrThrow<string>("API_KEY"),
SecretKey: configService.getOrThrow<string>("SECRET_KEY"),
},
};
},
};
}
export interface ISmsConfigs {
URL: string;
API_KEY: string;
SECRET_KEY: string;
SMS_PATTERN_OTP: string;
SMS_SECRET_BODY: {
UserApiKey: string;
SecretKey: string;
};
}
+1
View File
@@ -0,0 +1 @@
export const SMS_CONFIG = "SMS_CONFIG";
+18
View File
@@ -0,0 +1,18 @@
export interface ISmsBody {
ParameterArray: IParameterArray[];
Mobile: string;
TemplateId: string;
UserApiKey: string;
SecretKey: string;
}
export interface IParameterArray {
Parameter: string;
ParameterValue: string;
}
export interface ISmsResponse {
VerificationCodeId: number;
isSuccessful: boolean;
Message: string;
}
@@ -0,0 +1,35 @@
import { Inject, Injectable, Logger } from "@nestjs/common";
import axios from "axios";
import { ISmsConfigs } from "../../../configs/sms.config";
import { SMS_CONFIG } from "../constants";
import { ISmsBody } from "../interfaces/ISms";
@Injectable()
export class SmsService {
private logger = new Logger(SmsService.name);
constructor(@Inject(SMS_CONFIG) private smsConfigs: ISmsConfigs) {}
async sendSmsVerifyCode(mobile: string, otpCode: string) {
const smsData: ISmsBody = {
ParameterArray: [{ Parameter: "otp", ParameterValue: otpCode }],
Mobile: mobile,
TemplateId: this.smsConfigs.SMS_PATTERN_OTP,
...this.smsConfigs.SMS_SECRET_BODY,
};
return this.sendSms(smsData);
}
private async sendSms(body: ISmsBody) {
try {
const { data } = await axios.post(this.smsConfigs.URL, body, {
headers: {
"Content-Type": "application/json",
},
});
return data;
} catch (error) {
this.logger.error(error);
}
}
}
+11 -3
View File
@@ -1,7 +1,15 @@
import { Module } from "@nestjs/common";
import { SMS_CONFIG } from "./constants";
import { SmsConfigs } from "../../configs/sms.config";
@Module({
providers: [],
exports: [],
providers: [
{
provide: SMS_CONFIG,
useFactory: SmsConfigs().useFactory,
inject: SmsConfigs().inject
},
],
exports: [SMS_CONFIG]
})
export class UtilsModule {}
export class UtilsModule { }