Skip to content

Commit

Permalink
refactor: création de sms-service (separation des responsabilités)
Browse files Browse the repository at this point in the history
  • Loading branch information
Shamzic committed Nov 14, 2023
1 parent 8121c53 commit d8e452f
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 14 deletions.
24 changes: 24 additions & 0 deletions backend/lib/sms-service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import axios from "axios"
import config from "../config/index.js"

export async function renderAndSendSimulationResultsSms(followup) {
try {
const username = config.smsService.username
const password = config.smsService.password
if (!username || !password) {
throw new Error("Missing SMS service credentials")
}
const renderUrl = followup.renderSimulationResultsSmsUrl(username, password)
const axiosInstance = axios.create({
timeout: 10000,
})
const { data, status } = await axiosInstance.get(renderUrl)
if (status !== 200 || data.responseCode !== 0) {
throw new Error(`SMS request failed. Body: ${JSON.stringify(data)}`)
}
return data.messageIds[0]
} catch (err) {
console.error(err)
throw err
}
}
17 changes: 3 additions & 14 deletions backend/models/followup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import config from "../config/index.js"
import { Followup } from "../../lib/types/followup.d.js"
import { FollowupModel } from "../types/models.d.js"
import { phoneNumberFormatting } from "../../lib/phone-number.js"
import { renderAndSendSimulationResultsSms } from "../lib/sms-service.js"

const FollowupSchema = new mongoose.Schema<Followup, FollowupModel>(
{
Expand Down Expand Up @@ -114,20 +115,8 @@ FollowupSchema.method(

FollowupSchema.method("sendSimulationResultsSms", async function () {
try {
const username = config.smsService.username
const password = config.smsService.password
if (!username || !password) {
throw new Error("Missing SMS service credentials")
}
const renderUrl = this.renderSimulationResultsSmsUrl(username, password)
const axiosInstance = axios.create({
timeout: 10000,
})
const { data, status } = await axiosInstance.get(renderUrl)
if (status !== 200 || data.responseCode !== 0) {
throw new Error(`SMS request failed. Body: ${JSON.stringify(data)}`)
}
return this.postSimulationResultsSms(data.messageIds[0])
const messageId = await renderAndSendSimulationResultsSms(this)
return this.postSimulationResultsSms(messageId)
} catch (err) {
this.smsError = JSON.stringify(err, null, 2)
throw err
Expand Down

0 comments on commit d8e452f

Please sign in to comment.