Cloud Function For Firebase
GITS Indonesia
Sudaryatno
Technical Lead GITS Indonesia
Serverless, function as service (Faas)
Adalah cloud computing code execution model dimana cloud provider dapat
memanage secara meyeluruh, menjalankan dan memberhentikan container
dari setiam function.
Dan harga yang harus dibayarkan adalah ekesuti dari function tersebut bukan
per VM, per hit API, per Jam
Progression Serverless
Vendor Severless
AWS Lamda
Firebase Function
Microsoft Azure
IBM OpenWisk
Price Firebase Function
Intro
Cloud Function adalah tempat hosting yang private dan scalable untuk Node.js
environment.
Firebase SDK sekarang sudah terintegrasi dengan Cloud Function yang dapat
meresponse dan merequest fitur lain dari Firebase
Key capabilities
● Integrate The Firebase Platform
● Zero maintenance
● Keep your logic private and secure
Implement Path
Set up Functions Write Functions Deploy & Monitor
Function Start
npm install -g firebase-tools
myproject
+- .firebaserc # Hidden file that helps you quickly switch between
| # projects with `firebase use`
+- firebase.json # Describes properties for your project
+- functions/ # Directory containing all your functions code
+- package.json # npm package file describing your Cloud Functions code
+- index.js # main source file for your Cloud Functions code
+- node_modules/ # directory where your dependencies (declared in
# package.json) are installed
Perform Realtime
Database sanitization
and maintenance
1. Event user melakukan write di
database realtime
2. Function membaca action dan
juga dapat membrikan logic
dari action tersebut
3. Function menulis kembali di
database realtime dengan path
yang sama atau berbeda
GITS CODE Perform Realtime Database sanitization and maintenance
exports.makeUppercase = functions.database.ref('/messages/{pushId}/original').onWrite(event => {
// Grab the current value of what was written to the Realtime Database.
const original = event.data.val();
console.log('Uppercasing', event.params.pushId, original);
const uppercase = original.toUpperCase();
// You must return a Promise when performing asynchronous tasks inside a Functions such as
// writing to the Firebase Realtime Database.
// Setting an "uppercase" sibling in the Realtime Database returns a Promise.
return event.data.ref.parent.child('uppercase').set(uppercase);
Execute intensive task in
the cloud instead of in
your app
1. Function mendapatkan trigger
dari user yang upload image
2. Function download image dan
membuat versi thumbnail
3. Function menyimpan path
thumbnail di database
4. Function upload ulang ke
firebase storage
GITS CODE
return mkdirp(tempLocalDir).then(() => {
// Download file from bucket.
const bucket = gcs.bucket(event.data.bucket);
return bucket.file(filePath).download({
destination: tempLocalFile
}).then(() => {
console.log('The file has been downloaded to', tempLocalFile);
// Generate a thumbnail using ImageMagick.
return spawn('convert', [tempLocalFile, '-thumbnail', `${THUMB_MAX_WIDTH}x${THUMB_MAX_HEIGHT}>`, tempLocalThumbFile]).then(() => {
console.log('Thumbnail created at', tempLocalThumbFile);
// Uploading the Thumbnail.
return bucket.upload(tempLocalThumbFile, {
destination: thumbFilePath
}).then(() => {
console.log('Thumbnail uploaded to Storage at', thumbFilePath);
});
});
});
});
Integrate with third-party
service and APIs
1. Function dapat triger dari
webhook github
2. Function memanggil api
postMessage
GITS CODE
exports.githubWebhook = functions.https.onRequest((req, res) => {
const cipher = 'sha1';
const signature = req.headers['x-hub-signature'];
// TODO: Configure the `github.secret` Google Cloud environment variables.
const hmac = crypto.createHmac(cipher, functions.config().github.secret)
// The JSON body is automatically parsed by Cloud Functions so we re-stringify it.
.update(JSON.stringify(req.body, null, 0))
.digest('hex');
const expectedSignature = `${cipher}=${hmac}`;
// Check that the body of the request has been signed with the GitHub Secret.
if (signature === expectedSignature) {
postToSlack(req.body.compare, req.body.commits.length, req.body.repository).then(() => {
res.end();
}).catch(error => {
console.error(error);
res.status(500).send('Something went wrong while posting the message to Slack.');
});
} else {
console.error('x-hub-signature', signature, 'did not match', expectedSignature);
res.status(403).send('Your x-hub-signature's bad and you should feel bad!');
}});
Full Sample
https://github.com/firebase/functions-
samples
Google Cloud Functions is Google's serverless compute
solution for creating event-driven applications. It is a joint
product between the Google Cloud Platform team and the
Firebase team.
Thanks!
Contact us:
Sudaryatno
GITS Indonesia
Bandung, Mars Barat 1 no 9
yatnosudar@gits.co.id
www.gits.id

Cloud Function For Firebase - GITS

  • 1.
    Cloud Function ForFirebase GITS Indonesia
  • 2.
  • 4.
    Serverless, function asservice (Faas) Adalah cloud computing code execution model dimana cloud provider dapat memanage secara meyeluruh, menjalankan dan memberhentikan container dari setiam function. Dan harga yang harus dibayarkan adalah ekesuti dari function tersebut bukan per VM, per hit API, per Jam
  • 5.
  • 6.
    Vendor Severless AWS Lamda FirebaseFunction Microsoft Azure IBM OpenWisk
  • 7.
  • 8.
    Intro Cloud Function adalahtempat hosting yang private dan scalable untuk Node.js environment. Firebase SDK sekarang sudah terintegrasi dengan Cloud Function yang dapat meresponse dan merequest fitur lain dari Firebase
  • 9.
    Key capabilities ● IntegrateThe Firebase Platform ● Zero maintenance ● Keep your logic private and secure
  • 10.
    Implement Path Set upFunctions Write Functions Deploy & Monitor
  • 11.
    Function Start npm install-g firebase-tools
  • 12.
    myproject +- .firebaserc #Hidden file that helps you quickly switch between | # projects with `firebase use` +- firebase.json # Describes properties for your project +- functions/ # Directory containing all your functions code +- package.json # npm package file describing your Cloud Functions code +- index.js # main source file for your Cloud Functions code +- node_modules/ # directory where your dependencies (declared in # package.json) are installed
  • 13.
    Perform Realtime Database sanitization andmaintenance 1. Event user melakukan write di database realtime 2. Function membaca action dan juga dapat membrikan logic dari action tersebut 3. Function menulis kembali di database realtime dengan path yang sama atau berbeda
  • 14.
    GITS CODE PerformRealtime Database sanitization and maintenance exports.makeUppercase = functions.database.ref('/messages/{pushId}/original').onWrite(event => { // Grab the current value of what was written to the Realtime Database. const original = event.data.val(); console.log('Uppercasing', event.params.pushId, original); const uppercase = original.toUpperCase(); // You must return a Promise when performing asynchronous tasks inside a Functions such as // writing to the Firebase Realtime Database. // Setting an "uppercase" sibling in the Realtime Database returns a Promise. return event.data.ref.parent.child('uppercase').set(uppercase);
  • 15.
    Execute intensive taskin the cloud instead of in your app 1. Function mendapatkan trigger dari user yang upload image 2. Function download image dan membuat versi thumbnail 3. Function menyimpan path thumbnail di database 4. Function upload ulang ke firebase storage
  • 16.
    GITS CODE return mkdirp(tempLocalDir).then(()=> { // Download file from bucket. const bucket = gcs.bucket(event.data.bucket); return bucket.file(filePath).download({ destination: tempLocalFile }).then(() => { console.log('The file has been downloaded to', tempLocalFile); // Generate a thumbnail using ImageMagick. return spawn('convert', [tempLocalFile, '-thumbnail', `${THUMB_MAX_WIDTH}x${THUMB_MAX_HEIGHT}>`, tempLocalThumbFile]).then(() => { console.log('Thumbnail created at', tempLocalThumbFile); // Uploading the Thumbnail. return bucket.upload(tempLocalThumbFile, { destination: thumbFilePath }).then(() => { console.log('Thumbnail uploaded to Storage at', thumbFilePath); }); }); }); });
  • 17.
    Integrate with third-party serviceand APIs 1. Function dapat triger dari webhook github 2. Function memanggil api postMessage
  • 18.
    GITS CODE exports.githubWebhook =functions.https.onRequest((req, res) => { const cipher = 'sha1'; const signature = req.headers['x-hub-signature']; // TODO: Configure the `github.secret` Google Cloud environment variables. const hmac = crypto.createHmac(cipher, functions.config().github.secret) // The JSON body is automatically parsed by Cloud Functions so we re-stringify it. .update(JSON.stringify(req.body, null, 0)) .digest('hex'); const expectedSignature = `${cipher}=${hmac}`; // Check that the body of the request has been signed with the GitHub Secret. if (signature === expectedSignature) { postToSlack(req.body.compare, req.body.commits.length, req.body.repository).then(() => { res.end(); }).catch(error => { console.error(error); res.status(500).send('Something went wrong while posting the message to Slack.'); }); } else { console.error('x-hub-signature', signature, 'did not match', expectedSignature); res.status(403).send('Your x-hub-signature's bad and you should feel bad!'); }});
  • 19.
  • 20.
    Google Cloud Functionsis Google's serverless compute solution for creating event-driven applications. It is a joint product between the Google Cloud Platform team and the Firebase team.
  • 21.
    Thanks! Contact us: Sudaryatno GITS Indonesia Bandung,Mars Barat 1 no 9 yatnosudar@gits.co.id www.gits.id

Editor's Notes

  • #5 Adalah cloud computing code execution model dimana cloud provider dapat memanage secara meyeluruh, menjalankan dan memberhentikan container dari setiam function. Dan harga yang harus dibayarkan adalah ekesuti dari function tersebut bukan per VM, per hit API, per Jam
  • #6 https://www.slideshare.net/AmazonWebServices/a-brief-look-at-serverless-architecture
  • #9 Contoh dari google function dapat membuat API, meresponse listener dari firebase dan juga dapat di integrasikan dengan produk google yang lainnnya
  • #12 npm install -g firebase-tools
  • #16 Execute intensive tasks in the cloud instead of in your app A function triggers when an image file is uploaded to Storage. The function downloads the image and creates a thumbnail version of it. The function writes that thumbnail location to the database, so a client app can find and use it. The function uploads the thumbnail back to Storage in a new location.
  • #18 Integrate with third-party services and APIs