From da224c36ed7ea935ff702df0ed4b6b41431037d6 Mon Sep 17 00:00:00 2001 From: Brendan Chen Date: Mon, 10 Feb 2025 13:21:48 -0800 Subject: [PATCH] use node.js http2 module instead of fetch --- src/services/NotificationService.ts | 49 ++++++++++++++++++++++------- 1 file changed, 38 insertions(+), 11 deletions(-) diff --git a/src/services/NotificationService.ts b/src/services/NotificationService.ts index e4e202a..c6d7711 100644 --- a/src/services/NotificationService.ts +++ b/src/services/NotificationService.ts @@ -3,6 +3,7 @@ import jwt from "jsonwebtoken"; import fs from "fs"; import { TupleKey } from "../types/TupleKey"; import { IEta } from "../entities/entities"; +import * as http2 from "node:http2"; export interface ScheduledNotificationData { deviceId: string; @@ -103,31 +104,57 @@ export class NotificationService { } const headers = { - authorization: `bearer ${this.apnsToken}`, + ':method': 'POST', + ':path': `/3/device/${deviceId}`, + 'authorization': `bearer ${this.apnsToken}`, "apns-push-type": "alert", "apns-expiration": "0", "apns-priority": "10", "apns-topic": bundleId, }; try { - const response = await fetch(url, { - method: "POST", - headers, - body: JSON.stringify({ + const client = http2.connect('https://api.development.push.apple.com'); + const req = client.request(headers); + req.setEncoding('utf8'); + + await new Promise((resolve, reject) => { + req.on('response', (headers, flags) => { + if (headers[":status"] !== 200) { + console.error(`APNs request failed with status ${headers[":status"]}`); + reject(); + } + resolve(); + }); + + req.write(JSON.stringify({ aps: { alert: { title: "Shuttle is arriving", body: `Shuttle is approaching ${stop.name} in ${Math.ceil(eta.secondsRemaining / 60)} minutes.` } } - }), + })); + req.end(); }); - const json = await response.json(); - if (response.status !== 200) { - console.error(`Notification failed for device ${deviceId}:`, json.reason); - return false; - } + // const response = await fetch(url, { + // method: "POST", + // headers, + // body: JSON.stringify({ + // aps: { + // alert: { + // title: "Shuttle is arriving", + // body: `Shuttle is approaching ${stop.name} in ${Math.ceil(eta.secondsRemaining / 60)} minutes.` + // } + // } + // }), + // }); + // const json = await response.json(); + + // if (response.status !== 200) { + // console.error(`Notification failed for device ${deviceId}:`, json.reason); + // return false; + // } return true; } catch(e) { console.error(e);