Tiven Wang
Wang Tiven September 09, 2017
425 favorite favorites
bookmark bookmark
share share


在 Google firebase console 上创建项目 try-serverless-firebase,或者在 firebase cli 工具里创建项目。

安装 firebase cli 工具:

npm install -g firebase-tools

登录 firebase 账号

firebase login

初始化 Google Cloud functions 功能

firebase init functions

Hello world

./functions/index.js 里编写程序如下:

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

// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');

// Take the text parameter passed to this HTTP endpoint and insert it into the
// Realtime Database under the path /messages/:pushId/original
exports.addMessage = functions.https.onRequest((req, res) => {
  // Grab the text parameter.
  const original = req.query.text;
  // Push the new message into the Realtime Database using the Firebase Admin SDK.
  admin.database().ref('/messages').push({original: original}).then(snapshot => {
    // Redirect with 303 SEE OTHER to the URL of the pushed object in the Firebase console.
    res.redirect(303, snapshot.ref);

部署此 function 到 firebase 上:

firebase deploy --only functions or firebase deploy --only functions:addMessage

在 firebase console functions 栏里会出现这一条记录

Function Event Executions Median run time
addMessage HTTP Request https://us-central1-try-serverless-firebase.cloudfunctions.net/addMessage - -

在浏览器打开链接 https://us-central1-try-serverless-firebase.cloudfunctions.net/addMessage?text=Hello world! 它会跳转到 Firebase Realtime Database 里此条 Message 页面,因为我们在程序里指定了这样的返回:

res.redirect(303, snapshot.ref);

Event-driven Functions

Serverless 架构实现的核心概念就是事件驱动的函数. 想要实现自己的逻辑, 只需要编写当某个事件发生时所要执行的函数即可. 例如接下来我们要实现把保存的text转换成大写字母, 可以编写一个 on write original 事件所要执行的函数:

// Listens for new messages added to /messages/:pushId/original and creates an
// uppercase version of the message to /messages/:pushId/uppercase
// [START makeUppercaseTrigger]
exports.makeUppercase = functions.database.ref('/messages/{pushId}/original')
    .onWrite(event => {
// [END makeUppercaseTrigger]
  // [START makeUppercaseBody]
  // 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);
  // [END makeUppercaseBody]

使用Firebase封装好的函数来为数据库的某个消息字段保存时指定函数逻辑: functions.database.ref('/messages/{pushId}/original').onWrite(event => { ... });

重新部署之后, 再次调用addMessage url 可以看到消息如下:

|--- original: "Hello world!"
|--- uppercase: "HELLO WORLD!"



comments powered by Disqus
Back to Top