iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 19
0
Modern Web

認真學前端開發 - 以 TodoList 為例系列 第 19

Day19 - 使用 Firebase 來做儲存 [Part1]

  • 分享至 

  • twitterImage
  •  

將 Todo 內容存到 Serverless 上

寫了 TodoList 網頁但總是要把內容放到網路上,這樣才能將代辦清代記起來!

今天想要將機器存放在雲端 server 上,但不要自己去管理伺服器

Serverless 就像是一個 function 的服務,只要呼叫對方,對方就會幫忙把資料存起來,或者做某種計算

Severles 的提供商有很多,而這裡想要研究使用 firebase 來做 demo 和練習

Firebase

是由 Google 提供的 Serverles 服務,他有提供以下幾種服務

  • 帳號認證
  • 資料庫
  • 資料儲存
  • 架站
  • Functions

而我這次只需要使用 databas 資料庫的部分

以下會介紹 firebase-database 的使用紀錄

登入

進入 https://console.firebase.google.com/

登入 google 帳號

新增 Project

第一次登入需要創建一個專案

https://ithelp.ithome.com.tw/upload/images/20181103/20105814rAWaiUZEGV.png

我取個 todolist 來當我的名字

創建 Database

在左邊會看到 Database -> 選擇後會看到 這個

https://ithelp.ithome.com.tw/upload/images/20181103/20105814GHcmnrnHzQ.png

這邊我創建一個測試用的 database 是開放的所以使用上不用登入

如何使用 Database

大部分會參考這份文件

https://firebase.google.com/docs/database/web/start

設定 Firebase

Initialize the Realtime Database JavaScript SDK
You must specify your Realtime Database URL when initializing your JavaScript SDK.

官方說要提供 config 設定,給 JavaScript SDK

可以跟著以下步驟找到自己的 config 設定

先在左邊找到 Setting

https://ithelp.ithome.com.tw/upload/images/20181103/20105814CP8ddn6cc4.png

會看到 project 的資訊

往下有個 javascript 的 Setup 按鈕教學

https://ithelp.ithome.com.tw/upload/images/20181103/20105814AtLtggZ7Hh.png

點選後出現

https://ithelp.ithome.com.tw/upload/images/20181103/201058149cMYfzF9yX.png

接下來複製代碼到測試環境就可以玩 db 了

如何使用 db

上面有看到 firebase.initializeApp(config); 這段

可以使用 firebase 來對 db 進行操作

這邊是讀跟寫的教學

Write 範例

function writeUserData(userId, name, email, imageUrl) {
  // 一定要給 ref, reference 可以 database 說是要創造什麼資料
  // 這個例子是會創一個 users 的 collection
  // 裡面會個物件
  firebase.database().ref('users/' + userId).set({
    username: name,
    email: email,
    profile_picture : imageUrl
  });
}

有點難懂但看執行結果就很簡單了

writeUserData(1, 'john', 'john@smith.com, http://imgur/test)
writeUserData(2, 'alex', 'alex@xandar.com, http://imgur/test2)

Database 會把它存成這個

{
  "users" : {
    "1" : {
      "username" : "john",
      "email" : "john@smith.com"
      "profile_picture" : "http://imgur/test"
    },
    "2" : {
      "username" : "john",
      "email" : "john@smith.com"
      "profile_picture" : "http://imgur/test"
    }
  }
}

讀取資料

使用 ref 來 監聽 會讀取一次 DB

var starCountRef = firebase.database().ref('posts/' + postId + '/starCount');

這樣子會取得 ref

然後使用這個可以決定要

* 監聽

starCountRef.on('value', function(snapshot) {
  updateStarCount(postElement, snapshot.val());
});

監聽要小心地使用,官方建議是用在最底下的資料
盡量不要監聽在資料最外層

  • 讀一次
starCountRef.once('value').then(function(snapshot) {
  updateStarCount(postElement, snapshot.val());
});

讀一次的好處是,資料不常更新,可能就剛起來的時候用到,那就讀一次

今天已經搞懂了 Firebase Database 怎麼運作了,明天來測試看看怎麼使用它來做 TodoList 的儲存吧!


上一篇
Day-18 提高程式品質
下一篇
Day20 - 使用 Firebase 來做儲存 [Part2]
系列文
認真學前端開發 - 以 TodoList 為例30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言