| 1 | import * as OneSignal from '@onesignal/node-onesignal'; |
| 2 | |
| 3 | import { Injectable } |
| 4 | import { ConfigService } |
| 5 | |
| 6 | /** |
| 7 | * Thin wrapper around the OneSignal node SDK for sending push notifications |
| 8 | * to specific subscription (player) IDs. |
| 9 | */ |
| 10 | @Injectable() |
| 11 | export class OneSignalService |
| 12 | private readonly appId |
| 13 | private readonly client |
| 14 | |
| 15 | constructor(private readonly |
| 16 | this.appId = |
| 17 | const restApiKey = |
| 18 | 'ONESIGNAL_REST_API_KEY', |
| 19 | ); |
| 20 | |
| 21 | if (this.appId |
| 22 | const configuration = |
| 23 | this.client = |
| 24 | } else { |
| 25 | this.client = |
| 26 | console.warn( |
| 27 | 'OneSignal not configured (missing ONESIGNAL_APP_ID / ONESIGNAL_REST_API_KEY). Push notifications are disabled.', |
| 28 | ); |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | get enabled(): |
| 33 | return this.client |
| 34 | } |
| 35 | |
| 36 | /** |
| 37 | * Send a push notification to one or more subscription (player) IDs. |
| 38 | * Silently no-ops when OneSignal is not configured or no recipients given. |
| 39 | */ |
| 40 | async sendToPlayers( |
| 41 | playerIds: string[] |
| 42 | title: string, |
| 43 | message: string, |
| 44 | data?: Record |
| 45 | ): Promise<void |
| 46 | if (!this.client |
| 47 | const recipients = |
| 48 | if (recipients.length |
| 49 | |
| 50 | const notification = |
| 51 | notification.app_id = |
| 52 | notification.target_channel = |
| 53 | notification.include_subscription_ids = |
| 54 | notification.headings = |
| 55 | notification.contents = |
| 56 | if (data) notification |
| 57 | |
| 58 | try { |
| 59 | await this.client |
| 60 | console.log( |
| 61 | `OneSignal: sent "${title}" to ${ |
| 62 | ); |
| 63 | } catch (error) |
| 64 | console.error('OneSignal: failed to send notification: |
| 65 | } |
| 66 | } |
| 67 | } |