這邊我們重新打開googleHomeTrigger的function專案,利用node js加入 pub/sub的client端。
npm install @google-cloud/pubsub
新增config.ts
export const pubsubConfig = {
projectId : 'your-project',
topicName : 'your-topicName'
}
而在index.ts新增
const {PubSub} = require('@google-cloud/pubsub');
import { pubsubConfig } from './config'
const pubsub = new PubSub(pubsubConfig.projectId);
這邊則是主要進行判斷的部分,依據我的專案情況推播訊息
exports.googleHomeTrigger = functions.firestore.document('personal-accounts/{firebaseId}/peoples/{tagMac}')
.onUpdate(async (change, context) => {
const beforeData = change.before.data() as peopleInterface
const afterData = change.after.data() as peopleInterface
const physiologicalState = verifyPhysiologicalState(beforeData, afterData)
await notifyPhysiological(physiologicalState, afterData)
.catch(err =>console.log(err))
});
以及
//for object
const dataBuffer = Buffer.from(JSON.stringify(notifyMessage));
//for string
// const dataBuffer = Buffer.from(notifyMessage);
const messageId = await pubsub.topic(pubsubConfig.topicName).publish(dataBuffer);
console.log(`Message: ${messageId} published.`);