-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathfcm.provider.ts
132 lines (118 loc) · 3.66 KB
/
fcm.provider.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
import {
ChannelTypeEnum,
ISendMessageSuccessResponse,
IPushOptions,
IPushProvider,
} from '@novu/stateless';
import { initializeApp, cert, deleteApp, getApp } from 'firebase-admin/app';
import {
AndroidConfig,
ApnsConfig,
FcmOptions,
getMessaging,
Messaging,
WebpushConfig,
} from 'firebase-admin/messaging';
import crypto from 'crypto';
export class FcmPushProvider implements IPushProvider {
id = 'fcm';
channelType = ChannelTypeEnum.PUSH as ChannelTypeEnum.PUSH;
private appName: string;
private messaging: Messaging;
constructor(
private config: {
projectId: string;
email: string;
secretKey: string;
}
) {
this.config = config;
this.appName = crypto.randomBytes(32).toString();
const firebase = initializeApp(
{
credential: cert({
projectId: this.config.projectId,
clientEmail: this.config.email,
privateKey: this.config.secretKey,
}),
},
this.appName
);
this.messaging = getMessaging(firebase);
}
async sendMessage(
options: IPushOptions
): Promise<ISendMessageSuccessResponse> {
delete (options.overrides as { deviceTokens?: string[] })?.deviceTokens;
const overridesData = options.overrides || ({} as any);
const payload = this.cleanPayload(options.payload);
const androidData: AndroidConfig = overridesData.android;
const apnsData: ApnsConfig = overridesData.apns;
const fcmOptionsData: FcmOptions = overridesData.fcmOptions;
const webPushData: WebpushConfig = overridesData.webPush;
delete overridesData.android;
delete overridesData.apns;
delete overridesData.fcmOptions;
delete overridesData.webPush;
let res;
if (overridesData?.type === 'data') {
delete (options.overrides as { type?: string })?.type;
res = await this.messaging.sendMulticast({
tokens: options.target,
data: {
...payload,
title: options.title,
body: options.content,
message: options.content,
},
...(androidData ? { android: androidData } : {}),
...(apnsData ? { apns: apnsData } : {}),
...(fcmOptionsData ? { fcmOptions: fcmOptionsData } : {}),
...(webPushData ? { webpush: webPushData } : {}),
});
} else {
const { data, ...overrides } = overridesData;
res = await this.messaging.sendMulticast({
tokens: options.target,
notification: {
title: options.title,
body: options.content,
...overrides,
},
data,
...(androidData ? { android: androidData } : {}),
...(apnsData ? { apns: apnsData } : {}),
...(fcmOptionsData ? { fcmOptions: fcmOptionsData } : {}),
...(webPushData ? { webpush: webPushData } : {}),
});
}
if (res.successCount === 0) {
throw new Error(
`Sending message failed due to "${
res.responses.find((i) => i.success === false).error.message
}"`
);
}
const app = getApp(this.appName);
await deleteApp(app);
return {
ids: res?.responses?.map((response, index) =>
response.success
? response.messageId
: `${response.error.message}. Invalid token:- ${options.target[index]}`
),
date: new Date().toISOString(),
};
}
private cleanPayload(payload: object): Record<string, string> {
const cleanedPayload: Record<string, string> = {};
Object.keys(payload).forEach((key) => {
if (typeof payload[key] === 'string') {
cleanedPayload[key] = payload[key];
} else {
cleanedPayload[key] = JSON.stringify(payload[key]);
}
});
return cleanedPayload;
}
}