我尝试制作股票监控应用程序,用户可以在价格变动时Alert
。{/ p>
我有Stock
文档,我定期从第三方API获取。
在Stock
更新后,我会获取满足条件的所有Alert
,并通过Firebase消息通知用户。
这是我的模特。
/stocks/{stockId}
id: String
price: Number
/alerts/{alertId}
stockId: String
price: Number
condition: [moreThan, lessThan]
uid: String // User who create alert
/users/{userId}
id: String
fcmToken: String
我每5分钟获取一次最新股票价格并更新股票凭证= number of stock
写入查询。
function updateStockPrice(): Promise<FirebaseFirestore.WriteResult[]> {
const db = admin.firestore();
const options = {
// Options for stock api
};
return client(options)
.then(function(body) {
let batch = db.batch()
for(var stock in body){
let data = // create data from json response
let docRef = db.collection("stocks").doc(//id from 3rd party api)
batch.set(docRef, data)
}
return batch.commit()
});
}
库存写入更新,循环播放警报并从相关用户获取fcm令牌以发送推送通知=(alert query
+ number of alerts matched condition for user query
)x number of stock update
export const onStocksUpdate = functions.firestore.document('stocks/{stockId}').onWrite(function(change, context) {
const db = admin.firestore()
const newValue = change.after.data();
const previousValue = change.before.data();
const stockId = Number(context.params.stockId)
let p1 = db.collection("alerts")
.where("stockId", "==", stockId)
.where("condition", "==", "moreThan")
.where("price", "<=", newValue.lastPrice)
.get()
.then(function(querySnapshot) {
const promises = []
querySnapshot.forEach(function(doc) {
let data = doc.data()
let user = db.collection("users").doc(data.uid).get()
user.then(function(snapshot) {
let userData = snapshot.data()
return userData.fcmToken
}).then(function(fcmToken) {
const payload = {
notification: {
title: // title,
body: // body
},
token: fcmToken
}
return admin.messaging().send(payload)
}).catch(function(error) {
console.log(error)
})
promises.push(user)
})
return Promise.all(promises)
}).then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
return p1
})
总写= number of stock
总读数=(alert query
+ number of alerts matched condition for user query
)x number of stock update
假设我有20个股票,1个用户有3个警报。
每5分钟我将使用20个写查询和(1 + 3)x 20 = 80读
1天= 5760写和23,040读
对于这么小的例子来说,这似乎太多了。这是我应该布置数据结构的正确方法吗?或者有更好的方法吗?