Skip to content

Commit 5cbe2c7

Browse files
committed
chore(demo): retry on invalid_player_ids
1 parent cb4e412 commit 5cbe2c7

3 files changed

Lines changed: 102 additions & 71 deletions

File tree

examples/demo/src/services/OneSignalApiService.ts

Lines changed: 45 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -74,34 +74,54 @@ class OneSignalApiService {
7474
subscriptionId: string,
7575
extra: Record<string, unknown>,
7676
): Promise<boolean> {
77-
try {
78-
const body = {
79-
app_id: this.appId,
80-
include_subscription_ids: [subscriptionId],
81-
headings,
82-
contents,
83-
...extra,
84-
};
85-
86-
const response = await CapacitorHttp.post({
87-
url: 'https://onesignal.com/api/v1/notifications',
88-
headers: {
89-
Accept: 'application/vnd.onesignal.v1+json',
90-
'Content-Type': 'application/json',
91-
},
92-
data: body,
93-
});
94-
95-
if (response.status < 200 || response.status >= 300) {
96-
console.error(`Send notification failed: ${JSON.stringify(response.data)}`);
77+
const body = {
78+
app_id: this.appId,
79+
include_subscription_ids: [subscriptionId],
80+
headings,
81+
contents,
82+
...extra,
83+
};
84+
85+
// Retry once on `invalid_player_ids` to absorb the brief race where the
86+
// subscription has been created locally but is not yet visible to the
87+
// /notifications endpoint.
88+
for (let attempt = 0; attempt < 2; attempt++) {
89+
try {
90+
const response = await CapacitorHttp.post({
91+
url: 'https://onesignal.com/api/v1/notifications',
92+
headers: {
93+
Accept: 'application/vnd.onesignal.v1+json',
94+
'Content-Type': 'application/json',
95+
},
96+
data: body,
97+
});
98+
99+
if (response.status < 200 || response.status >= 300) {
100+
console.error(`Send notification failed: ${JSON.stringify(response.data)}`);
101+
return false;
102+
}
103+
104+
const data = response.data as { errors?: { invalid_player_ids?: unknown } } | undefined;
105+
const invalidIds = data?.errors?.invalid_player_ids;
106+
if (Array.isArray(invalidIds) && invalidIds.length > 0) {
107+
if (attempt === 0) {
108+
await new Promise((resolve) => setTimeout(resolve, 3_000));
109+
continue;
110+
}
111+
console.error(
112+
`Send notification failed: invalid_player_ids ${JSON.stringify(invalidIds)}`,
113+
);
114+
return false;
115+
}
116+
117+
return true;
118+
} catch (err) {
119+
console.error(`Send notification error: ${String(err)}`);
97120
return false;
98121
}
99-
100-
return true;
101-
} catch (err) {
102-
console.error(`Send notification error: ${String(err)}`);
103-
return false;
104122
}
123+
124+
return false;
105125
}
106126

107127
async updateLiveActivity(

examples/demo_pods/src/hooks/useOneSignal.ts

Lines changed: 12 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,18 @@ const RESOLVED_APP_ID = APP_ID?.trim() || DEFAULT_APP_ID;
1818
const apiService = OneSignalApiService.getInstance();
1919
const preferences = PreferencesService.getInstance();
2020

21+
// uncomment to debug ios logs in safari web inspector
22+
// const buf: string[] = [];
23+
// (['log', 'warn', 'error'] as const).forEach((level) => {
24+
// const orig = console[level].bind(console);
25+
// console[level] = (...args) => {
26+
// buf.push(`[${level}] ${args.map(String).join(' ')}`);
27+
// localStorage.setItem('__logs', JSON.stringify(buf.slice(-500)));
28+
// orig(...args);
29+
// };
30+
// });
31+
// then later call JSON.parse(localStorage.getItem('__logs')).forEach(l => console.log(l))
32+
2133
// One-shot SDK initialization at module-eval time. Capacitor's bridge queues
2234
// calls until native is ready, so no `deviceready` gating is required. The
2335
// downstream `OneSignal.initialize` short-circuits on the native side, but
@@ -196,22 +208,6 @@ export function useOneSignal(): UseOneSignalReturn {
196208

197209
const handleNotificationClick = (e: NotificationClickEvent) => {
198210
console.log(`Notification click: ${e.notification.title ?? ''}`);
199-
// Persist to localStorage so cold-start clicks are still inspectable
200-
// after the Safari Web Inspector reattaches to the WKWebView.
201-
try {
202-
const existing = JSON.parse(localStorage.getItem('lastNotificationClicks') ?? '[]');
203-
existing.push({
204-
notificationId: e.notification.notificationId,
205-
title: e.notification.title ?? null,
206-
body: e.notification.body ?? null,
207-
actionId: e.result.actionId ?? null,
208-
url: e.result.url ?? null,
209-
receivedAt: new Date().toISOString(),
210-
});
211-
localStorage.setItem('lastNotificationClicks', JSON.stringify(existing.slice(-20)));
212-
} catch (err) {
213-
console.warn('Failed to persist notification click to localStorage', err);
214-
}
215211
};
216212

217213
const handleForegroundWillDisplay = (e: NotificationWillDisplayEvent) => {
@@ -255,11 +251,6 @@ export function useOneSignal(): UseOneSignalReturn {
255251
OneSignal.User.addEventListener('change', userChangeHandler);
256252

257253
const load = async () => {
258-
// Uncomment if you want so you have time to see logs while trying to open
259-
// safari web inspector. Not an issue for chrome web inspector.
260-
// await new Promise((resolve) => setTimeout(resolve, 10_000));
261-
// if (cancelled) return;
262-
263254
const [externalId, pushId, pushOptedIn, hasPerm, initialOnesignalId] = await Promise.all([
264255
OneSignal.User.getExternalId(),
265256
OneSignal.User.pushSubscription.getIdAsync(),

examples/demo_pods/src/services/OneSignalApiService.ts

Lines changed: 45 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -74,34 +74,54 @@ class OneSignalApiService {
7474
subscriptionId: string,
7575
extra: Record<string, unknown>,
7676
): Promise<boolean> {
77-
try {
78-
const body = {
79-
app_id: this.appId,
80-
include_subscription_ids: [subscriptionId],
81-
headings,
82-
contents,
83-
...extra,
84-
};
85-
86-
const response = await CapacitorHttp.post({
87-
url: 'https://onesignal.com/api/v1/notifications',
88-
headers: {
89-
Accept: 'application/vnd.onesignal.v1+json',
90-
'Content-Type': 'application/json',
91-
},
92-
data: body,
93-
});
94-
95-
if (response.status < 200 || response.status >= 300) {
96-
console.error(`Send notification failed: ${JSON.stringify(response.data)}`);
77+
const body = {
78+
app_id: this.appId,
79+
include_subscription_ids: [subscriptionId],
80+
headings,
81+
contents,
82+
...extra,
83+
};
84+
85+
// Retry once on `invalid_player_ids` to absorb the brief race where the
86+
// subscription has been created locally but is not yet visible to the
87+
// /notifications endpoint.
88+
for (let attempt = 0; attempt < 2; attempt++) {
89+
try {
90+
const response = await CapacitorHttp.post({
91+
url: 'https://onesignal.com/api/v1/notifications',
92+
headers: {
93+
Accept: 'application/vnd.onesignal.v1+json',
94+
'Content-Type': 'application/json',
95+
},
96+
data: body,
97+
});
98+
99+
if (response.status < 200 || response.status >= 300) {
100+
console.error(`Send notification failed: ${JSON.stringify(response.data)}`);
101+
return false;
102+
}
103+
104+
const data = response.data as { errors?: { invalid_player_ids?: unknown } } | undefined;
105+
const invalidIds = data?.errors?.invalid_player_ids;
106+
if (Array.isArray(invalidIds) && invalidIds.length > 0) {
107+
if (attempt === 0) {
108+
await new Promise((resolve) => setTimeout(resolve, 3_000));
109+
continue;
110+
}
111+
console.error(
112+
`Send notification failed: invalid_player_ids ${JSON.stringify(invalidIds)}`,
113+
);
114+
return false;
115+
}
116+
117+
return true;
118+
} catch (err) {
119+
console.error(`Send notification error: ${String(err)}`);
97120
return false;
98121
}
99-
100-
return true;
101-
} catch (err) {
102-
console.error(`Send notification error: ${String(err)}`);
103-
return false;
104122
}
123+
124+
return false;
105125
}
106126

107127
async updateLiveActivity(

0 commit comments

Comments
 (0)