【发布时间】:2019-06-13 03:54:43
【问题描述】:
我目前正在使用 Firebase firestore 和 Next JS。我已经用谷歌搜索了如何组织一个 firestore 项目,但其中大多数(实际上都是)不可扩展。
我尝试创建一个文件夹,其中包含所有与 Firebase 相关的组件,例如配置和实用程序方法。我发现最具挑战性的部分是编写一个通用函数来获取应用所有支持的方法的集合/文档引用,即.orderBy()、.limit()、.where() 和.doc()。编写一个将数据库返回的数据转换为另一种格式的转换器也非常困难。
这是我已经实现的:
getDocRef.js 是一个辅助函数,将上述所有方法放在一起,getOnce.js 和 observe.js 公开与数据库交互的方法,db.js 包含配置。
另外,对于任何感兴趣的人,这是我对 .getDocRef() 函数的幼稚解决方案:
import db from '../db';
/*
Options:
- ref: Specify the ref of a document
- collectionName: Specify the collection name
- queryArgs: Specify the arguments to be passed down to .where()
- orderByArgs: Specify the arguments to be passed down to .orderBy()
- limit: Specify the fetching limit
- docName: Specify the document name/id
*/
export default options => {
const { ref, collectionName, queryArgs, orderByArgs, limit, docName } = options;
if (ref != null) return ref;
const initRef = db.collection(collectionName);
if (docName != null) return initRef.doc(docName);
if (queryArgs != null) {
if (orderByArgs != null) {
if (limit != null)
return initRef
.where(...queryArgs)
.orderBy(...orderByArgs)
.limit(limit);
return initRef.where(...queryArgs).orderBy(...orderByArgs);
}
return initRef.where(...queryArgs);
}
return initRef;
};
所以,我很想知道我当前的 Firebase 实现是否正常。如果不是,我应该应用什么项目结构?我应该如何改进我目前的结构以使其更有效?最后但并非最不重要的一点是,上面发布的我的幼稚 JS 解决方案是否有替代方案?提前致谢
【问题讨论】:
标签: reactjs firebase google-cloud-firestore next.js