dpd-fcm
Version:
send push notif to client, using Firebase Cloud Messaging
70 lines (58 loc) • 2.14 kB
JavaScript
var Resource = require('deployd/lib/resource'),
util = require('util'),
Client = require('node-rest-client').Client,
client = new Client(),
firebaseURL = "https://fcm.googleapis.com/fcm/send"
function FCM(name, options) {
Resource.apply(this, arguments);
}
util.inherits(FCM, Resource);
FCM.prototype.clientGeneration = true;
FCM.basicDashboard = {
settings: [
{
name : 'internalOnly',
type : 'checkbox',
description : 'Only allow internal scripts to send push notification'
},
{
name : 'serverKey',
type : 'text',
description : 'Make sure this is the server key, whose value is available in your Firebase project console under Project Settings > Cloud Messaging. Android, iOS, and browser keys are rejected by FCM.'
}]
};
FCM.prototype.handle = function (ctx, next) {
if ( ctx.req && ctx.req.method !== 'POST' ) {
return next();
}
if ( !ctx.req.internal && this.config.internalOnly ) {
return ctx.done({ statusCode: 403, message: 'Forbidden' });
}
var options = ctx.body || {};
var sKey = this.config.serverKey || process.env.FCM_SERVER_KEY;
// set content-type header and data as json in args parameter
var args = {
data: options,
headers: {
"Content-Type": "application/json",
"Authorization": "key="+sKey
}
};
client.post(firebaseURL, args, function (data, response) {
var rCode = response.statusCode;
// parsed response body as js object
console.log(data);
// raw response
console.log(response);
if (rCode === 200) {
ctx.done(null, data);
} else if (rCode === 401) {
ctx.done({ statusCode: response.statusCode, errors: "FCM Server Key Unauthorized!" });
} else if (rCode === 400) {
ctx.done({ statusCode: response.statusCode, errors: "Bad Request, check body params! https://firebase.google.com/docs/cloud-messaging/http-server-ref#params" });
} else {
ctx.done({ statusCode: response.statusCode, errors: "Something went wrong!" });
}
});
}
module.exports = FCM;