firebase-fcm-v1-http2
Version:
A Node.js library for sending push notifications using Firebase Cloud Messaging HTTP v1 APIs.
57 lines (56 loc) • 2.58 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Client = void 0;
const utils_1 = require("./utils");
const fcm_1 = require("./fcm");
class Client {
constructor(options) {
if (!options.serviceAccount) {
throw new Error('Please provide the service account JSON configuration file.');
}
this.config = {
serviceAccount: options.serviceAccount,
maxConcurrentConnections: options.maxConcurrentConnections || Client.defaultMaxConcurrentConnections,
maxConcurrentStreamsAllowed: options.maxConcurrentStreamsAllowed || Client.defaultMaxConcurrentStreamsAllowed
};
}
sendMulticast(message, tokens) {
return new Promise((resolve, reject) => {
let batchLimit = Math.ceil(tokens.length / this.config.maxConcurrentConnections);
const tokenBatches = [];
if (batchLimit <= this.config.maxConcurrentStreamsAllowed) {
batchLimit = this.config.maxConcurrentStreamsAllowed;
}
for (let start = 0; start < tokens.length; start += batchLimit) {
tokenBatches.push(tokens.slice(start, start + batchLimit));
}
const unregisteredTokens = [];
const projectId = this.config.serviceAccount.project_id;
if (!projectId) {
return reject(new Error('Unable to determine Firebase Project ID from service account file.'));
}
(0, utils_1.getAccessToken)(this.config.serviceAccount).then((accessToken) => {
let done = 0;
for (const tokenBatch of tokenBatches) {
(0, fcm_1.processBatch)(message, tokenBatch, projectId, accessToken, this.config.maxConcurrentStreamsAllowed, this.config.maxConcurrentConnections)
.then((unregisteredTokensList) => {
if (unregisteredTokensList.length > 0)
unregisteredTokens.push(...unregisteredTokensList);
done++;
if (done === tokenBatches.length) {
resolve(unregisteredTokens);
}
})
.catch((err) => {
reject(err);
});
}
}).catch((err) => {
reject(err);
});
});
}
}
exports.Client = Client;
Client.defaultMaxConcurrentConnections = 10;
Client.defaultMaxConcurrentStreamsAllowed = 100;