Skip to content

Commit 0ccf95a

Browse files
committed
Allow overriding GCM API key with a sendNotification argument.
Fixes #181.
1 parent 612b558 commit 0ccf95a

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

index.js

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,8 @@ function sendNotification(endpoint, params) {
131131

132132
return new Promise(function(resolve, reject) {
133133
try {
134+
var curGCMAPIKey = gcmAPIKey;
135+
134136
if (args.length === 0) {
135137
throw new Error('sendNotification requires at least one argument, the endpoint URL.');
136138
} else if (params && typeof params === 'object') {
@@ -139,6 +141,9 @@ function sendNotification(endpoint, params) {
139141
var userAuth = params.userAuth;
140142
var payload = params.payload;
141143
var vapid = params.vapid;
144+
if (params.gcmAPIKey) {
145+
curGCMAPIKey = params.gcmAPIKey;
146+
}
142147
} else if (args.length !== 1) {
143148
throw new Error('You are using the old, deprecated, interface of the `sendNotification` function.');
144149
}
@@ -187,11 +192,11 @@ function sendNotification(endpoint, params) {
187192

188193
var isGCM = endpoint.indexOf('https://android.googleapis.com/gcm/send') === 0;
189194
if (isGCM) {
190-
if (!gcmAPIKey) {
195+
if (!curGCMAPIKey) {
191196
console.warn('Attempt to send push notification to GCM endpoint, but no GCM key is defined'.bold.red);
192197
}
193198

194-
options.headers['Authorization'] = 'key=' + gcmAPIKey;
199+
options.headers['Authorization'] = 'key=' + curGCMAPIKey;
195200
}
196201

197202
if (vapid && !isGCM) {

test/testSendNotification.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -356,6 +356,34 @@ suite('sendNotification', function() {
356356
});
357357
});
358358

359+
test('send/receive string with GCM (overriding the GCM API key)', function() {
360+
var httpsrequest = https.request;
361+
https.request = function(options, listener) {
362+
options.hostname = '127.0.0.1';
363+
options.port = serverPort;
364+
options.path = '/';
365+
return httpsrequest.call(https, options, listener);
366+
}
367+
368+
webPush.setGCMAPIKey('another_gcm_api_key');
369+
370+
return startServer('hello', undefined, undefined, true)
371+
.then(function() {
372+
return webPush.sendNotification('https://android.googleapis.com/gcm/send/someSubscriptionID', {
373+
userPublicKey: urlBase64.encode(userPublicKey),
374+
userAuth: urlBase64.encode(userAuth),
375+
payload: 'hello',
376+
gcmAPIKey: 'my_gcm_key',
377+
});
378+
})
379+
.then(function(body) {
380+
assert(true, 'sendNotification promise resolved');
381+
assert.equal(body, 'ok');
382+
}, function() {
383+
assert(false, 'sendNotification promise rejected');
384+
});
385+
});
386+
359387
test('0 arguments', function() {
360388
return webPush.sendNotification()
361389
.then(function() {

0 commit comments

Comments
 (0)