Skip to content

Cloud Function – Part 1 : Install, Functions, Deployment

Installation

npm install [email protected] [email protected] --save
npm install -g firebase-tools

firebase login
firebase init firestore
firebase init functions

npm install

Test & Deploy

Test : firebase emulators:start

or firebase emulators:start --only functions

Deploy : $ firebase deploy --only functions

OnCall Function

exports.addMessage = functions.https.onCall((data, context) => {
	
  // Message text passed from the client.
  const text = data.text;

  // Authentication / user information is automatically added to the request.
  const uid = context.auth.uid;
  const name = context.auth.token.name || null;
  const picture = context.auth.token.picture || null;
  const email = context.auth.token.email || null;


  if (!context.auth) {
    throw new functions.https.HttpsError('failed-precondition', 'The function must be called while authenticated.');
  }

  // returning result.
  return { ... };
});

Call Function at Client with SDK

firebase.initializeApp({...});

var functions = firebase.functions();

var addMessage = firebase.functions().httpsCallable('addMessage');

addMessage({text: messageText}).then(function(result) {
  var sanitizedMessage = result.data.text;

}).catch(function(error) {
  var code = error.code;
  var message = error.message;
  var details = error.details;

});

OnRequest (for API build)

with Nodejs Express

const express = require('express');
const cors = require('cors');

const app = express();

// Automatically allow cross-origin requests
app.use(cors({ origin: true }));

// Add middleware to authenticate requests
app.use(myMiddleware);

// build multiple CRUD interfaces:
app.get('/:id', (req, res) => res.send(Widgets.getById(req.params.id)));
app.post('/', (req, res) => res.send(Widgets.create()));
app.put('/:id', (req, res) => res.send(Widgets.update(req.params.id, req.body)));
app.delete('/:id', (req, res) => res.send(Widgets.delete(req.params.id)));
app.get('/', (req, res) => res.send(Widgets.list()));

// Expose Express API as a single Cloud Function:
exports.widgets = functions.https.onRequest(app);

Deploy

All Functions :

$ firebase deploy --only functions

Only Select Functions :

$ firebase deploy --only functions:addMessage,functions:makeUppercase

Delete Function

# Delete all functions that match the specified name in all regions.
$ firebase functions:delete myFunction

# Delete a specified function running in a specific region.
$ firebase functions:delete myFunction --region us-east-1

# Delete more than one function
$ firebase functions:delete myFunction myOtherFunction

# Delete a specified functions group.
$ firebase functions:delete groupA

# Bypass the confirmation prompt.
$ firebase functions:delete myFunction --force

Rename

# Deploy new function called webhookNew
$ firebase deploy --only functions:webhookNew

# Wait until deployment is done; now both webhookNew and webhook are running

# Delete webhook
$ firebase functions:delete webhook

And more about region changes, trigger type change

Group Deploy

const functions = require('firebase-functions');
exports.usageStats = functions.https.onRequest((request, response) => {
  // ...
});
exports.nightlyReport = functions.https.onRequest((request, response) => {
  // ...
});

metrics.js

exports.metrics = require('./metrics');

index.js

Run this : firebase deploy --only functions:metrics

Logging

  const functions = require("firebase-functions");

  functions.logger.log("Hello from info. Here's an object:", someObj);
  • logger.log() commands have the INFO log level.
  • logger.info() commands have the INFO log level.
  • logger.warn() commands have the ERROR log level.
  • logger.error() commands have the ERROR log level.
  • Internal system messages have the DEBUG log level.

hoặc cứ dụng Console.log

exports.helloError = functions.https.onRequest((request, response) => {
  console.log('I am a log entry!');
  response.send('Hello World...');
});
  • console.log() commands have the INFO log level.
  • console.info() commands have the INFO log level.
  • console.warn() commands have the ERROR log level.
  • console.error() commands have the ERROR log level.
  • Internal system messages have the DEBUG log level.

View Log

firebase functions:log

firebase functions:log --only <FUNCTION_NAME>

firebase help functions:log

Published inCloud Function

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *