extract code to open and close the apns connection

This commit is contained in:
2025-04-30 17:49:39 -07:00
parent 075b35e7ad
commit 06d2a7bb27

View File

@@ -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;
}
}