*Cloud Functions 作法
const { initializeApp } = require('firebase-admin/app');
const { getFirestore } = require('firebase-admin/firestore');
initializeApp();
const db = getFirestore();
*自架 ServerserviceAccountKey.json
:透過 Google Cloud console,選擇服務帳戶-> 點擊新增金鑰-> 類型 JSON
const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
const { getFirestore } = require('firebase-admin/firestore');
const serviceAccount = require('./path/to/serviceAccountKey.json');
initializeApp({
credential: cert(serviceAccount)
});
const db = getFirestore();
*和 Client 端用法大致相同
// set() 指定 document ID
await db.collection('movies').doc(movies-id').set(data);
// add() 使用系統隨機 document ID
await db.collection('movies').add({
name: 'Sing Street',
date: '2016'
});
// update() 更新 data 欄位
const movieRef = db.collection('movies').doc(movies-id);
await movieRef.update({date: 2023});
// 取得 collection 所有 document
const moviesRef = db.collection('movies');
const snapshot = await moviesRef.get();
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
});
// FieldValue.delete() 刪除 data 特定 field
// 先取得 document 參照
const movieRef = db.collection('movies').doc(movies-id);
// 移除 date
const res = await movieRef.update({
date: FieldValue.delete()
});
編輯 Cloud Function index.js
設定 Firebase Admin SDK
// index.js
const functions = require('@google-cloud/functions-framework');
const axios = require("axios");
const cheerio = require("cheerio");
const url = "https://meet.eslite.com/tw/tc/gallery/movieschedule/201803020001";
// 設定 Firebase
const { initializeApp, cert } = require('firebase-admin/app');
const { getFirestore } = require('firebase-admin/firestore');
initializeApp({
projectId: "xxxxxxx"
});
const db = getFirestore();
functions.http('getTimetable', async(req, res) => {
try {
// 略
// 增加 document 到 collection "movies"
list.forEach(async(item) => {
const res = await db.collection('movies').add({...item});
})
res.status(200).send(list);
} catch (e) {
console.log(e)
}
})
*Firestore 資料呈現