前置作業
首先,在 Firebase 創建一個應用程式,並且創建一個 Firestore 資料庫。如果是由後端程式存取資料庫,則可以選取「鎖定模式」,避免資源被濫用。
為了讓後端程式存取資料庫,需要創建一個憑證。點選「專案設定」、「服務帳戶」,然後點選「產生新的私密金鑰」,將憑證下載到專案目錄中。
建立專案
建立專案。
1 2
| mkdir firebase-firestore-node-example cd firebase-firestore-node-example
|
初始化專案。
安裝依賴套件。
1
| npm install firebase firebase-admin
|
修改 package.json
檔。
新增 .gitignore
檔。
1 2 3
| /node_modules /.vscode serviceAccountKey.json
|
操作資料庫
新增 index.mjs
檔。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| import { cert, initializeApp } from 'firebase-admin/app'; import { getFirestore } from 'firebase-admin/firestore'; import serviceAccount from './serviceAccountKey.json' assert { type: 'json' };
const app = initializeApp({ credential: cert(serviceAccount), });
class Storage { constructor(collection) { const db = getFirestore(app); this.collection = db.collection(collection); }
async getCount() { return (await this.collection.count().get()).data().count; }
async setItem(key, value) { await this.collection.doc(key).set(value); }
async getItem(key) { return (await this.collection.doc(key).get()).data(); }
async fetchItems() { const items = {}; const snapshot = await this.collection.get(); snapshot.forEach((item) => { items[item.id] = item.data(); }); return items; }
async removeItem(key) { await this.collection.doc(key).delete(); } }
const storage = new Storage('links');
(async () => { console.log(await storage.getCount()); await storage.setItem('0', { foo: 'bar' }); console.log(await storage.fetchItems()); await storage.removeItem('0'); })();
|
程式碼
參考資料