Skip to content

Instantly share code, notes, and snippets.

@PetkevichPavel
Last active August 24, 2019 08:14
Show Gist options
  • Save PetkevichPavel/8fecba4cbd2ce6888c9fde78c25d1fd7 to your computer and use it in GitHub Desktop.
Save PetkevichPavel/8fecba4cbd2ce6888c9fde78c25d1fd7 to your computer and use it in GitHub Desktop.
Cloud function: common class.
"use strict";
import functions = require("firebase-functions");
import admin = require("firebase-admin");
import * as rcFunctions from './RemoteConfigFunctions';
import { RemoteConfigObj } from "./RemoteConfigObj";
import * as secretProps from '../SecretProperties';
const request = require('request');
const STATUS_CODE_OK = 200
Object.defineProperty(exports, "__esModule", { value: true });
admin.initializeApp({
credential: admin.credential.cert(secretProps.service),
databaseURL: secretProps.DB_URL
});
exports.showConfigDiff = functions.remoteConfig.onUpdate(async (param) => {
// Here is a payload for the future notification.
const payload = {
notification: {
title: 'New updates',
body: 'We have updated our app remote config.'
},
// Also I have here some specific data for the remote config only,
// by which I can easily discern the basic notification from the
//remote config notification.
data: {
"rc_extra_back_notification": "true"
}
};
rcFunctions.getAccessToken(secretProps.service).then(token => {
//After a successful token request, we will compose
//the options for the future request.
const options = {
uri: secretProps.FB_URL_RC,
method: 'GET',
gzip: true,
resolveWithFullResponse: true,
headers: {
'Authorization': 'Bearer ' + token,
'Accept-Encoding': 'gzip',
}
};
// Here we will run the request on remote config.
// As a response we will have: error, response: { statusCode } and body.
request(options, function (error: any, response: { statusCode: any; },
body: any) {
console.log('statusCode:', response && response.statusCode);
if (response.statusCode === STATUS_CODE_OK) {
console.log('body:', body);
const obj: RemoteConfigObj = JSON.parse(body);
const platformSettings =
JSON.parse(obj.parameters.platform_setting.defaultValue.value);
if (platformSettings !== null) {
console.log("platformSettings: " + platformSettings.isItDev + "," + platformSettings.isPushAvailable + ", " + platformSettings.platform);
const topic = rcFunctions.choosePushTopics(platformSettings)
console.log("topic: " + topic.length);
if (topic.length !== 0) {
topic.forEach(async (top) => {
console.log("Topic: " + top);
// And finally, we will send the notifications to our topic/s.
const resp =
await admin.messaging().sendToTopic(top, payload);
console.log(resp);
})
}
}
} else console.error('error:', error);
});
}).catch(er => console.error('error:', er))
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment