From 06d2a7bb277138efab0efeb56240d1bba1e5f711 Mon Sep 17 00:00:00 2001 From: Brendan Chen Date: Wed, 30 Apr 2025 17:49:39 -0700 Subject: [PATCH] extract code to open and close the apns connection --- .../senders/AppleNotificationSender.ts | 39 +++++++++++++------ 1 file changed, 28 insertions(+), 11 deletions(-) diff --git a/src/notifications/senders/AppleNotificationSender.ts b/src/notifications/senders/AppleNotificationSender.ts index 61c0b73..ebe20f0 100644 --- a/src/notifications/senders/AppleNotificationSender.ts +++ b/src/notifications/senders/AppleNotificationSender.ts @@ -86,7 +86,9 @@ export class AppleNotificationSender { throw new Error("APNS_BUNDLE_ID environment variable is not set correctly"); } - const { path, host } = AppleNotificationSender.getAPNsFullUrlToUse(deviceId); + this.openConnectionIfNoneExists(); + + const { path } = AppleNotificationSender.getAPNsFullUrlToUse(deviceId); const headers = { ':method': 'POST', @@ -98,9 +100,7 @@ export class AppleNotificationSender { "apns-topic": bundleId, }; try { - if (!this.client) { - this.client = http2.connect(host); - } + if (!this.client) { return false } const client = this.client; const req = client.request(headers); req.setEncoding('utf8'); @@ -137,15 +137,21 @@ export class AppleNotificationSender { } } - public static getAPNsFullUrlToUse(deviceId: string): APNsUrl { - // Construct the fetch request - const devBaseUrl = "https://api.development.push.apple.com" - const prodBaseUrl = "https://api.push.apple.com" + private openConnectionIfNoneExists() { + const host = AppleNotificationSender.getAPNsHostToUse(); - let hostToUse = devBaseUrl; - if (process.env.APNS_IS_PRODUCTION === "1") { - hostToUse = prodBaseUrl; + if (!this.client) { + this.client = http2.connect(host); } + } + + private closeConnectionIfExists() { + this.client?.close(); + this.client = undefined; + } + + public static getAPNsFullUrlToUse(deviceId: string): APNsUrl { + let hostToUse = this.getAPNsHostToUse(); const path = "/3/device/" + deviceId; const fullUrl = hostToUse + path; @@ -157,4 +163,15 @@ export class AppleNotificationSender { }; } + public static getAPNsHostToUse() { + // Construct the fetch request + const devBaseUrl = "https://api.development.push.apple.com" + const prodBaseUrl = "https://api.push.apple.com" + + let hostToUse = devBaseUrl; + if (process.env.APNS_IS_PRODUCTION === "1") { + hostToUse = prodBaseUrl; + } + return hostToUse; + } }