Firestore使用数据库/服务器时间进行查询 [英] Firestore use database/server time for query

查看:52
本文介绍了Firestore使用数据库/服务器时间进行查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Firestore中有一个 collection ,其中包含接下来365天的字符串.实际上,这是我们的应用在特定日期需要显示的代码字.

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.

我们注意到,如果用户更改日期并返回到应用程序,则Firestore会正确返回当天的代码字,因为我们的查询使用今天的日期来查询代码字.

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.

以前,我们在服务器上有一个定制的API,该API将根据服务器的时间进行提取,以确保不会发生这种情况.

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

用Firestore复制此行为的最佳方法是什么?我能想到的唯一方法是每天停止将所有数据存储在数据库中,并从服务器托管的文件中注入数据.这可能是最好的方法,但想在选择此解决方案之前提出问题.

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.

这是我们当前的查询

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?

推荐答案

您不能在查询中使用服务器的时间,因为查询的值必须来自客户端.但是您可能可以保护数据,使其仅允许用户读取今天"的数据.而且由于您是在Firestore的服务器端安全规则中执行此操作的,因此可以在其中使用服务器端时间戳.

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.

您当前的查询可以使用基于以下条件的查询过滤器进行保护:文档字段 request.time 字段.

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

您还可以考虑进行上述查询,并且每个日期只创建一个文档,即具有诸如 2018-11-13 之类的ID,然后:1)让客户今天请求该文档,2)在安全规则中限制对该特定文档的访问.

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.

这篇关于Firestore使用数据库/服务器时间进行查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆