Firebase - Firebase functions 使用紀錄
on 2019-12-20
Firebase - Firebase functions 使用紀錄
最近想把一些自己在用的小東西丟到 severless 的服務
因為之前發生過一次 server 掛掉過一次的情況
當時是 GCP CE 不知為何 VM 中的網卡設定出問題
整個網卡消失
然後外部根本連不進去
最後請教大大後
只好開一個新的 instance 然後把原本的那個儲存空間掛到新開的 instance
因為那台平常在試驗的 server
裡面亂七八糟而且大多的 code 都不會做 git 控管
所以就想說把一些常用的功能用 serverless 拆出來好了
就想說來研究一下火了一陣子然後設定沒設定好就會噴一堆預算和安全性問題的 Firebase 所推出的 functions
其實 GCP 自己本身也有 cloud functions
但我這是玩票性質的
所以就先用 firebase functions 來試試啦
先說一下目前 firebase functions 只支援 Nodejs
但是 Google cloud 的 cloud functions 支援 Nodejs python golnag
- 首先先裝 firebase-tools CLI
npm install -g firebase-tools
- 執行 firebase login
firebase login
- 到要建立 functions 的資料夾
這時候要注意如果你要做版本控管
就是直接到該 repository 的目錄下即可
下一步會在這目錄建立需要的程式
- 執行 firebase init functions
firebase init functions
過程中會請你選擇或新開專案
這邊的專案是指 firebase 上面的專案
可以用 JavaScript
寫或 TypeScript
寫 code
整個 functions 的結構
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
|
+- .eslintrc.json # Optional file containing rules for JavaScript linting.
|
+- 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
要注意的事和開始寫扣啦
index.js 就是 functions 會執行的程式
你可以依照自己的需求安裝需要的 node 套件
但需要注意的是該套件安裝完你的 package.json
的 dependencies
必須有紀錄該套件的版號
package.json
中的
"engines": {
"node": "8"
}
表示使用的 node 版本
目前預設是 8
10 有支援但目前是 beta
可以看目前文件來決定用哪一版的 nodejs
exports.ok = functions.https.onRequest((request, response) => {
response.send("Hello from Firebase!");
});
ok 就會是實際上 url path
上線後的 url 會是
http://<region>-<firebase project name>.cloudfunctions.net/<exports name>
ex:
http://us-central1-my-project.cloudfunctions.net/ok
相關 API 可以參考
很多 API 都和 express 幾乎一樣
如果要帶參數的話可以用 params
部署區域
可以決定該功能在那個區域部署
同一個 index 檔案可以部署不同地區
預設是 us-central1 (Iowa) 艾荷華
可以查看支援的 region 列表
只要添加在 code 之中即可
exports.ok = functions.region('asia-northeast1').https.onRequest((request, response) => {
...
目前沒法在程式中直接設定 multi region 得一個一個上
不然官方是建議建立不同 region 的 entry
再把 function 邏輯抽象出來就可以了
本地測試
會在本地開啟 local server
也會有對應的 url path 可以讓你直接點
如果要測試 log
在 node 中寫
console.log()
console.info()
console.error()
console.warn()
就可以了
呼叫第三方或外部 api 時出現 EAI_AGAIN
查了一下
這是 DNS 解析的問題
在 Free 方案只允許呼叫 Google service 自己的 api
要切到付費方案才可以
用 Blaze plan 就可以了
Firebase - Firebase Cloud Message(FCM) Research Log
on 2016-12-08
Firebase - Firebase Cloud Message(FCM) Research Log
This article is focus on web version
Intro
You can easy to use web notification push notification to your web site.
Set Up a JavaScript Firebase Cloud Messaging Client App
Different with use pure web notification
- Browser support
- FCM - Chrome(desktop & Android) & Firefox(desktop & Android)
- pure notification api - Chrome(desktop & Android) & Firefox(desktop & Android) & Opera(desktop) & Safari(desktop)
- Android need service worker
- Service Worker
- FCM - require
- pure notification api - option
pure web notification only a notification object, you need handle connection push message from server.
But FCM had handle this connect.
Different whith use Service Worker or not use Service Worker
use Service Worker | no use Service Worker | |
---|---|---|
service open on browser tab and focus | receive | receive |
service open on browser tab and not focus | receive | receive |
service open not on browser tab | receive | can’t receive |
Prepare
- app server
- a server can send message
- HTTPS
- web service need https for handle Service Worker
- manifest.json
- set gcm send id
Step
-
Use firebase console create a project(If you had project for your web service, you can skip this setp
-
Overview -> setting -> cloud message
and you can getYOUR-SERVER-KEY
&SENDER-ID
-
And then you can use the simple code from https://github.com/firebase/quickstart-js/tree/master/messaging
FCM Flow
Web notification dosen’t have Instance ID
so we only can use token
Base flow
App server
Build it to send message or do something like send topic message or personal message
Use HTTP
or XMPP
Firebase Cloud Messaging HTTP Protocol
Personal push
You can bind user info & their token created from client web browser, then you can push personal message for user.
And it use api push notification like this
https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
{ "data": {
"score": "5x1",
"time": "15:10"
},
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
}
Authorization
key is Firebase console server key
Reference - Build App Server Send Requests
Multiple device push
Send Messages to Multiple Devices
It’s base on sub / pub pattern, you can reference Publish/Subscribe pattern - MSDN - Microsoft
Two way
-
topic(suggest) Suggest use this, it’s fast and easy to use
If you want to know any token push status and tracking which in this group, you can use group way
But you must handle group yourself
About Tracking
FCM web notification not support analytics
So you can add querystring on action url or add log on receive message on foreground
Error handle
If user clear token on offline, need handle cleared token let app server and IID server know
Two way can handle this thing
- client initiative handle
If your web service provide unsubscribe function, you must handle this behavior.
And you need handle if user clear data from client, you need update token.
Firebase’s api messaging.deleteToken()
handle delete from IID server but delete token from app server need handle yourself.
- server side detect
When server push notification and response error make some error handle like delete InvalidRegistration
token
And you can log token active time, if long time not active, you can delete it from app server and also suggest delete it from IID server
Notice
On desktop device Chrome or Firefox not on process it can not receive message
But message will queued until Browser open
So don’t worried about this thing
-
Notice don’t send error target user
-
Notice don’t send the push token that doesn’t had any user or device
And then i find Firebase hosting seem doesn’t support service worker, so it can’t use FCM on Firebase hosting.
Receive Messages in a JavaScript Client
Reference - Using the Notifications API - Web APIs | MDN
Reference - Publish/Subscribe pattern - MSDN - Microsoft