Firestore use database/server time for query

允我心安 提交于 2021-02-11 12:29:01

问题


I have a collection in Firestore that contains a string for the next 365 days. It's effectively a codeword that our app needs to display on that particular day.

We've noticed that if a user changes the date and comes back to the app, Firestore correctly returns the codeword for that day because our query uses today's date to query for the codeword.

Previously, we had a bespoke API on a server that would fetch based on the server's time to ensure this couldn't happen.

What would be the best way to replicate this behaviour with Firestore? The only way I can think is to stop storing all the data in the database and inject it from a server hosted file on a daily basis. This may well be the best way, but wanted to pose the question before choosing this solution.

Here's our current query

const codeword = await firebase
  .firestore()
  .collection('emoji')
  .where('valid_from', '>=', new Date())
  .limit(1)
  .orderBy('valid_from', 'asc')
  .get();

// today's codeword is "whatever" based on the client time
// ... can I use the server's time instead?

回答1:


You can't use the server's time in the query, since the value you query for has to come from the client. But you could probably secure the data to only allow the user to read the data for "today". And since you'd do that in Firestore's server-side security rules, you could use the server-side timestamp in it.

Your current query could be secured with a query-filter based on document fields and the request.time field.

You could also consider foregoing the query, and just making a single document each date, i.e. with a ID like 2018-11-13 and then: 1) have the client request the document for today, 2) restrict access to that specific document in security rules.



来源:https://stackoverflow.com/questions/53283805/firestore-use-database-server-time-for-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!