Hexo NexT 主題的閱讀次數統計

發表於
分類於 教學

這是一個在 Next 主題上的小功能可以在文章及首頁顯示文章的閱讀次數使用了 firestore 作為資料庫 之前發的 PR

需要 Next v5.1.4 以上的版本

更新: 目前已不建議使用此插件

預覽圖

使用教學

取得 firestore 資料庫

firebase 網站 創建一個專案 專案名稱之類的都可以自己選

創建專案

接下來創建完成之後在左側選擇 Database 會出現選擇資料庫的頁面在這個步驟請選擇右側的 Cloud Firestore

選擇資料庫

然後選擇 以測試模式啟動 (之後會再設定安全性)

選擇模式

設定 _config.yml

在上面的步驟建立完成 firestore 資料庫之後按照下面的圖片裡的 1,2 點擊然後會看到圖片中的資訊,projectid 和 apikey 是待會在設定檔裡面要用到的

取得apikey

接下來開啟主題的_config.yml (themes/next/_config.yml) 並且找到 firestore的部分預設值:

# Another tool to show number of visitors to each article.
# visit https://console.firebase.google.com/u/0/ to get apiKey and projectId
# visit https://firebase.google.com/docs/firestore/ to get more information about firestore
firestore:
	enable: false
	collection: articles #required, a string collection name to access firestore database
	apiKey: #required
	projectId: #required
	bluebird: false #enable this if you want to include bluebird 3.5.1(core version) Promise polyfill

enable設定成true 然後把前面得到的apikeyprojectId填入對應的欄位中 collection改不改都行,不知道這是什麼的話請別更改

collection 的值會影響閱讀次數的數值儲存在哪裡

如果需要支援一些老舊的瀏覽器請把bluebird設定成true

Bluebird 為了支援 Promise ,詳細的相容性可以到 MDN 上看

改完的 _config.yml:

firestore:
	enable: true
	collection: articles
	apiKey: YOUR_API_KEY #required
	projectId: hexo-next-firestore-example #required
	bluebird: true

測試

接下來執行hexo s啟動測試伺服器應該要在首頁的每篇文章的標題下面看到閱讀次數

然後點進任何一篇文章也要在標題下面看到閱讀次數

預覽圖

firestore 安全設定

這個步驟可做可不做

接下來在 firebase 裡面回到 Database 頁面,然後選擇上面的規則

firestore規則

把裡面的值改成下面的來限制只有articles這個 collection 可以被修改如果在前面的設定裡的collection的值不是articles的話下面也要修改

service cloud.firestore {
	match /databases/{database}/documents {
		match /articles/{any} {
			allow read: if true;
			allow write: if request.resource.data.count==resource.data.count+1;
		}
	}
}

後記

會弄出這個功能的原因是不想使用原本就有的 LeanCloud 統計功能 (這個的設定方法比較簡單) 所以就自己用 javascript 來簡單的實作了一個統計次數的功能然後發 PR 給主題